I'm using Java's java.util.Date
class in Scala and want to compare a Date
object and the current time. I know I can calculate the delta by using getTime():
(new java.util.Date()).getTime() - oldDate.getTime()
However, this just leaves me with a long
representing milliseconds. Is there any simpler, nicer way to get a time delta?
Best Answer
Simple diff (without lib)
And then can you call:
to get the diff of the 2 dates in minutes unit.
TimeUnit
isjava.util.concurrent.TimeUnit
, a standard Java enum going from nanos to days.Human readable diff (without lib)
http://ideone.com/5dXeu6
The output is something like
Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}
, with the units ordered.You just have to convert that map to an user-friendly string.
Warning
The above code snippets compute a simple diff between 2 instants. It can cause problems during a daylight saving switch, like explained in this post. This means if you compute the diff between dates with no time you may have a missing day/hour.
In my opinion the date diff is kind of subjective, especially on days. You may:
count the number of 24h elapsed time: day+1 - day = 1 day = 24h
count the number of elapsed time, taking care of daylight savings: day+1 - day = 1 = 24h (but using midnight time and daylight savings it could be 0 day and 23h)
count the number of
day switches
, which means day+1 1pm - day 11am = 1 day, even if the elapsed time is just 2h (or 1h if there is a daylight saving :p)My answer is valid if your definition of date diff on days match the 1st case
With JodaTime
If you are using JodaTime you can get the diff for 2 instants (millies backed ReadableInstant) dates with:
But you can also get the diff for Local dates/times: