Search code examples
timezoneequalsjodatimeutc

Why does the first Joda DateTime instance gets a non-UTC Chronology?


date1 and date2 are not equal here because of the different Chronologies:

val formatter = ISODateTimeFormat.dateTimeNoMillis
val date1 = formatter.parseDateTime("2012-01-03T00:00:00Z")
val date2 = new DateTime(2012, 1, 3, 0, 0, DateTimeZone.UTC)
println(date1.getChronology) // ISOChronology[Europe/Bucharest]
println(date2.getChronology) // ISOChronology[UTC]
assert(date1 === date2)      // fails

Here they're equal though:

val formatter = ISODateTimeFormat.dateTimeNoMillis
val date1 = formatter.withZone(DateTimeZone.UTC).parseDateTime("2012-01-03T00:00:00Z")
val date2 = new DateTime(2012, 1, 3, 0, 0, DateTimeZone.UTC)
println(date1.getChronology) // ISOChronology[UTC]
println(date2.getChronology) // ISOChronology[UTC]
assert(date1 === date2)      // succeeds

I know DateTime instances should have same Chronologies in order to be treated as equal, but I would have expected that the Z designator in the string would make the formatter parse date1 in the UTC Chronology. I'm pretty sure I'm confused on the difference between Chronology and DateTimeZone, so I'd really appreciate if someone can point it out what exactly is that I'm conflating.

BTW, the code is in Scala and the assertions are from ScalaTest, but this shouldn't make any difference.


Solution

  • Parsing will create a date-time in the default time-zone unless it is further configured. The "Z" is taken into account, but the time-of-day is then adjusted as necessary to match your time-zone (Bucharest).

    val date1 = formatter.withOffsetParsed().parseDateTime("2012-01-03T00:00:00Z")
    

    Add withOffsetParsed() to get the behaviour you want.