I have a string pattern for a formatter
yyyy-MM-dd HH:mm:ss Z
How to parse a java.util.Date using this pattern?
The problem is the time zone already in this pattern.
String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss Z";
DateTimeFormatter.ofPattern(DATE_TIME_FORMAT).format(date.toInstant());
This apparently gives
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
at java.time.Instant.getLong(Instant.java:603)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
The solutions here and in other places doesn't have timezone in the format string and offer solutions like:
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.ofInstant(dateD.toInstant(), ZoneId.systemDefault()))
Can I somehow parse it?
An Instant
does not have the notion of year of era:
The supported fields are:
- NANO_OF_SECOND
- MICRO_OF_SECOND
- MILLI_OF_SECOND
- INSTANT_SECONDS
You could use a ZonedDateTime instead:
ZonedDateTime zdt = date.toInstant().atZone(ZoneOffset.UTC);
String format = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT).format(zdt);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With