views:

36

answers:

1

How come this test I wrote fails in jodatime 1.6.2? Is it a bug?

@Test
 public void testIfJodaTimePeriodsHandlesPeriodTypesOtherThanMinutesAndHours() {
  long twentyDaysInMillis = TimeUnit.MILLISECONDS.convert(20, TimeUnit.DAYS);
  Period twoWeeks = new Period(twentyDaysInMillis, PeriodType.weeks());
  Assert.assertEquals(2, twoWeeks.getWeeks()); 
// twoWeeks.getWeeks() actually returns 0!!
 }

FYI, Periods with all PeriodTypes only fills in the fields for minutes and hours, even if the millis passed to the constructor amounts to more than 25 hours. This is counterintuitive.

+3  A: 

That's how Period works in JodaTime.

Period has precise fields (hours, minutes, seconds, milliseconds) and imprecise fields (other). Imprecise fields may be affected by daylight savings. That is, Period of 24 hours may be less than a day or more than a day on a daylight savings boundary.

Therefore, constructors that take milliseconds populate only precise fields. To initialize imprecise fields (without taking daylight savings in account) you need:

Period twoWeeks = new Period(twentyDaysInMillis).normalizedStandard(PeriodType.weeks()); 

See also:

axtavt
My bad for not reading the docs properly I guess. Thanks for the informative answer!
eirirlar