Personally I find the error message "Unsupported field: Year" misleading. The real cause is missing timezone. This information is needed to help the formatter to internally convert the given instant to a human-time-representation. Solution: Supply the timezone. Then formatting or parsing an Instant
is supported - in contrast to the answer of @flo.
Printing:
String s =
DateTimeFormatter.ofPattern("uuuu-MMM-dd HH:mm:ss", Locale.ENGLISH)
.withZone(ZoneId.systemDefault())
.format(Instant.now());
System.out.println(s); // 2015-Oct-30 15:22:32
Parsing:
The reverse procedure - parsing - does unfortunately not work the same direct way because the format engine of java.time
is designed such that the formatter only returns a raw TemporalAccessor
which needs to be converted to the real required type. Example:
Instant instant =
Instant.from(
DateTimeFormatter.ofPattern("uuuu-MMM-dd HH:mm:ss", Locale.ENGLISH)
.withZone(ZoneId.systemDefault())
.parse("2015-Oct-30 15:22:32"));
System.out.println("=>" + instant); // 2015-10-30T14:22:32Z
If the input to be parsed contains a timezone offset or an identifier then you can modify the pattern (symbols x, X, z, Z, VV etc.) and leave out the call to withZone(...)
, and in case of offsets - you really should leave out that call because otherwise the formatter will not use the timezone offset of your input but the supplied one zone (a pitfall I observed in my own tests).
yyyy
instead ofuuuu
– Cursiveyyyy
just throwsUnsupported field: Year of Era
instead ofUnsupported field: Year
. – LazuritetoMillis
instead oftoInstant
? Formatting anInstant
requires timezone. – CursivetoMillis
? – Lazurite