如何在 java.time 的模式字符串中格式化带时区的日期?

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

我有格式化程序的字符串模式

yyyy-MM-dd HH:mm:ss Z

如何使用此模式解析 java.util.Date?

问题是时区已经采用这种模式。

String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss Z";

DateTimeFormatter.ofPattern(DATE_TIME_FORMAT).format(date.toInstant());

这显然给了

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
    at java.time.Instant.getLong(Instant.java:603)
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)

此处和其他地方的解决方案在格式字符串中没有时区,并提供如下解决方案:

DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.ofInstant(dateD.toInstant(), ZoneId.systemDefault()))

我能以某种方式解析它吗?

一个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

您可以改用 ZonedDateTime:

ZonedDateTime zdt = date.toInstant().atZone(ZoneOffset.UTC);
String format = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT).format(zdt);