Tuesday 29 November 2016

Calculating the difference between two Java date instances



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?


Answer




The JDK Date API is horribly broken unfortunately. I recommend using Joda Time library.



Joda Time has a concept of time Interval:



Interval interval = new Interval(oldTime, new Instant());


EDIT: By the way, Joda has two concepts: Interval for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration that represents a length of time without the actual time boundaries (e.g. represent two hours!)



If you only care about time comparisions, most Date implementations (including the JDK one) implements Comparable interface which allows you to use the Comparable.compareTo()



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...