Calculating a time duration with Joda-Time

bloodcell picture bloodcell · Feb 13, 2011 · Viewed 11.2k times · Source

I'm trying to use Joda-Time in order to know time durations between two points in time, where each point is given in its own local timezone.

E.g. :

DateTime ny = new DateTime(2011, 2, 2, 7, 0, 0, 0, DateTimeZone.forID("America/New_York"));
DateTime la = new DateTime(2011, 2, 3, 10, 15, 0, 0, DateTimeZone.forID("America/Los_Angeles"));
DateTime utc1 = ny.withZone(DateTimeZone.UTC);
DateTime utc2 = la.withZone(DateTimeZone.UTC);        
Period period = new Period(utc1, utc2);

Now, I wish to know if this takes into account day light savings and leap years... Also, is the use of 'Period' the correct Joda-Time way to achieve this? Thanks ;)

Answer

Russ Hayward picture Russ Hayward · Feb 13, 2011

The code you provided will work and take into account time zones but you don't need to do the conversion to UTC. This code is simpler and does the same thing (using a Duration rather than a Period):

DateTime ny = new DateTime(2011, 2, 2, 7, 0, 0, 0, DateTimeZone.forID("America/New_York"));
DateTime la = new DateTime(2011, 2, 3, 10, 15, 0, 0, DateTimeZone.forID("America/Los_Angeles"));
Duration duration = new Interval(ny, la).toDuration();