Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
Gray Avatar asked Nov 17 '25 11:11

Gray


1 Answers

Turns out that Joda-time is wicked smaaaaart. 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());
like image 77
Gray Avatar answered Nov 19 '25 00:11

Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!