We currently in the process of replacing SimpleDateFormat
with DateTimeFormatter
.
During this I came across a weird behavior.
There is a difference in milliseconds which I can't explain to myself.
Here is the code:
val timeString = "2021-09-17T13:37:00.09Z"
val newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").withZone(ZoneId.of("UTC"))
val oldFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US)
val zonedDateTime = newFormatter.parse(timeString)
val newFormatterDate = Date.from(zonedDateTime.toInstant())
val oldFormatterDate = oldFormatter.parse(timeString)
Assert.assertEquals(newFormatterDate, oldFormatterDate) // false
// newFormatterDate.time is 1631885820090 and
// oldFormatterDate.time is 1631885820009
I found a lot of posts here stating that we shouldn't use SimpleDateFormat
anymore.
But can someone explain to me how this could happen? Do we have a bug in our code or misunderstood something?
Edit: The solution provided by @Ole V.V.'s link (How to parse date-time with two or three milliseconds digits in java?) may solve the bug I encounter but it does not answer the question/explain why these two formatters produce different results.