I was messing around with JodaTime today, and I expected this test to pass:
@Test
public void dateTimeShouldRoundTrip() {
DateTime originalDateTime = new DateTime(2013, 7, 4, 0, 0);
DateTime roundTrip = new DateTime(originalDateTime.toGregorianCalendar());
assertThat(roundTrip, is(originalDateTime));
}
But it fails. I checked it under both JodaTime 2.1 and 2.2.
Further inspection (using the SamePropertyValuesAs matcher) shows that the failure is caused by a difference in the centuryOfEra
property:
originalDateTime.getCenturyOfEra(); // 20
roundTrip.getCenturyOfEra(); // 21
So why does this property change, when everything else - year, month, day, day of week, timezone, etc. - does not? Is this a bug? Shouldn't you be able to roundtrip a DateTime to a Calendar and back again?
Joda Time version 2.2 has an isEqual method that compares only the milisecond, whereas equals compares the milisecond, chronology and timezone:
DateTime d = new DateTime();
new DateTime(d.toGregorianCalendar()).isEqual(d); // returns true
new DateTime(d.toGregorianCalendar()).equals(d); // returns false, as you observed
So either the chronology or timezone are not preserved by the conversion to or from a GregorianCalender. Leave a comment if you'd like me to investigate further.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With