views:

1535

answers:

5

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?

A: 

Not using the standard API, no. You can roll your own doing something like this:

class Duration {
    private final TimeUnit unit;
    private final long length;
    // ...
}

Or you can use Joda:

DateTime a = ..., b = ...;
Duration d = new Duration(a, b);
gustafc
+7  A: 

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 case about time comparisions, most Date implementations (including the JDK one) implements Comparable interface which allows you to use the Comparable.compare()

notnoop
Thanks. I guess it's time for me to bite the bullet and start using Joda Time.
pr1001
If you're using Joda Time with Scala, take a look at http://github.com/jorgeortiz85/scala-time/tree/master
Jorge Ortiz
We use JODA exclusively now
arcticpenguin
+3  A: 

Take a look at Joda Time, which is an improved Date/Time API for Java and should work fine with Scala.

Rob H
+1  A: 

That's probably the most straightforward way to do it - perhaps it's because I've been coding in Java (with its admittedly clunky date and time libraries) for a while now, but that code looks "simple and nice" to me!

Are you happy with the result being returned in milliseconds, or is part of your question that you would prefer to have it returned in some alternative format?

Andrzej Doyle
+4  A: 

A slightly simpler alternative:

System.currentTimeMillis() - oldDate.getTime()

As for "nicer": well, what exactly do you need? The problem with representing time durations as a number of hours and days etc. is that it may lead to inaccuracies and wrong expectations due to the complexity of dates (e.g. days can have 23 or 25 hours due to daylight savings time).

Michael Borgwardt