I'm trying to format an Instant to a String using the new java 8 time-api and a pattern:
Instant instant = ...;
String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant);
Using the code above I get an Exception which complains an unsupported field:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
at java.time.Instant.getLong(Instant.java:608)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
...
The
Instant
class doesn't contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC. So, formatter can't print a date because date always printed for concrete time zone. You should set time zone to formatter and all will be fine, like this :Or if you still want to use formatter created from pattern you can just use LocalDateTime instead of Instant:
I believe this might help, you may need to use some sort of localdate variation instead of instant
Time Zone
To format an
Instant
a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.The time-zone can be added directly to the formatter using
withZone()
.Generating String
Now use that formatter to generate the String representation of your Instant.
Dump to console.
When run.