Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format Date with time zone in pattern string in java.time?

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?

like image 593
Dia Avatar asked Apr 15 '15 12:04

Dia


1 Answers

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);
like image 73
assylias Avatar answered Sep 25 '22 06:09

assylias