Philipp Jardas
Philipp Jardas

Reputation: 3302

Joda: How to compare date instances in same time zone with different time zone representations?

I am trying to compare two Joda dates for equality in my unit tests. expected is created with new DateTime(...) while parsed is parsed from a string with DateTimeFormatter.

Although my date string contains the timezone fragment +02:00 the parsed date has the time zone Europe/Berlin. This is semantically correct (at least during DST), however the two dates do not equal.

I could, of course, create my expected time zone with DateTimeZone.forID("Europe/Berlin"), but that would not be totally correct IMHO. Europe/Berlin has an offset of +01:00 during winter and +02:00 during summer. The input string explicitly states +02:00, so my unit test would fail if the input date was in winter.

Any ideas on how to fix this?

Example code

DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
DateTime expected = new DateTime(2013, 6, 22, 11, 7, 22, 123, DateTimeZone.forOffsetHours(2));
String input = "2013-06-22T11:07:22.123+02:00";
DateTime parsed = formatter.parseDateTime(input);
System.out.println("expected: " + expected + " (" + expected.getChronology() + ")");
System.out.println("parsed  : " + parsed + " (" + parsed.getChronology() + ")");
System.out.println("equal   : " + expected.equals(parsed));

Example output

expected: 2013-06-22T11:07:22.123+02:00 (ISOChronology[+02:00])
parsed  : 2013-06-22T11:07:22.123+02:00 (ISOChronology[Europe/Berlin])
equal   : false

Upvotes: 1

Views: 583

Answers (1)

Philipp Jardas
Philipp Jardas

Reputation: 3302

Just found the answer myself. There's an option for DateTimeFormatter that prevents it from resolving time zone offsets:

ISODateTimeFormat.dateTime().withOffsetParsed()

Upvotes: 1

Related Questions