HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavaCritical

Calculating the difference between two Java date instances

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
instancesjavadatebetweenthedifferencetwocalculating

Problem

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?

Solution

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()

Code Snippets

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

Context

Stack Overflow Q#1555262, score: 214

Revisions (0)

No revisions yet.