According to Baeldung it is not possible to do this (Kotlin code):
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(Instant.ofEpochMilli(0L))
That is absolutely correct, as the execution results in:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
As I understand an Instant
, it is a moment in time, measured as the number of milliseconds since 1970-01-01T00:00:00.000Z. And the Instant
's ms are specifically counted using UTC as a globally unique reference. So why can I not print an Instant in UTC?
I have found numerous examples online that state exactly the same as Baeldung, you need a time zone to format an Instant
. For example this SO question. But none of them explain why it does not work. The only reason given is usually something along the lines of:
Without a time-zone, the formatter does not know how to convert the instant to human date-time fields.
That is not an answer to my question. I gave a pattern specifically stating UTC (Z
), yet the formatting fails. Since an Instant
contains UTC data, it should be able to be formatted as an ISO-8601 string. In this case the formatter should know how to convert the instant to human date-time fields.
I expect the above code to result in
"1970-01-01T00:00:00.000Z"
Why is this not the case? What is the design choice behind this?