Gray Gray - 1 month ago 7
Java Question

Joda-time Period doesn't seem to calculate days correctly

I am seeing some strange behavior around the Joda-time

Period
class -- specifically the days processing. In the following example code, I am specifying a period of 26 hours as milliseconds.

// 26 hour duration
long durationMillis = 26 * 3600 * 1000;
Period period = new Period(durationMillis, PeriodType.dayTime());
// this fails because days == 0
assertEquals(1, period.getDays());
// this would fail because hours == 26
assertEquals(2, period.getHours());


I was expecting that
Period
would see that 26 hours is 1 day and 2 hours but it doesn't seem to be recognizing that a day == 24 hours.

Any idea what am I doing wrong?

Answer

Turns out that Joda-time is wicket smaaart. I guess that it can't know the number of hours in a day because of daylight savings time and other timezone issues. There might be 23 or 25 hours in any particular day for example.

To force it to a 24 hours/day, you need to specific a Chronology that is consistent about hours per day.

long durationMillis = 26 * 3600 * 1000;
Period period = new Period(durationMillis, PeriodType.dayTime(),
    ISOChronology.getInstanceUTC());
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is needed to have 1 day == 24 hours
// this works!
assertEquals(1, period.getDays());
// this works!
assertEquals(2, period.getHours());