Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does converting a Joda DateTime to Calendar and back change the centuryOfEra field and nothing else?

Tags:

java

jodatime

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?

like image 328
Paul Phillips Avatar asked Jul 04 '13 05:07

Paul Phillips


1 Answers

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.

like image 140
hd1 Avatar answered Sep 28 '22 01:09

hd1