在 Java8 中使用时区设置 LocalDateTime 的格式

2022-08-31 07:35:26

我有这个简单的代码:

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
LocalDateTime.now().format(FORMATTER)

然后我会得到以下例外:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds
at java.time.LocalDate.get0(LocalDate.java:680)
at java.time.LocalDate.getLong(LocalDate.java:659)
at java.time.LocalDateTime.getLong(LocalDateTime.java:720)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$OffsetIdPrinterParser.format(DateTimeFormatterBuilder.java:3315)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1745)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1719)
at java.time.LocalDateTime.format(LocalDateTime.java:1746)

如何解决此问题?


答案 1

LocalDateTime 是没有时区的日期时间。但是,您在格式中指定了时区偏移量格式符号,但没有此类信息。这就是发生错误的原因。LocalDateTime

如果需要时区信息,则应使用 ZonedDateTime

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"

答案 2

JSR-310 中的前缀“Local”(在 Java-8 中也称为 java.time-package)并不表示存在处于该类内部状态的时区信息(此处:)。尽管名称经常具有误导性,但像LocalDateTimeLocalTime这样的类没有时区信息或偏移量LocalDateTime

您尝试使用偏移信息(由图案符号 Z 指示)格式化此类时态类型(不包含任何偏移)。因此,格式化程序尝试访问不可用的信息,并且必须引发您观察到的异常。

溶液:

使用具有此类偏移量或时区信息的类型。在 JSR-310 中,这是(包含偏移量,但不包含 DST 规则的时区)或 。您可以通过查找方法isSupported(TemporalField)来观察此类类型的所有受支持字段。该字段在 和 中受支持,但在 中不受支持。OffsetDateTimeZonedDateTimeOffsetSecondsOffsetDateTimeZonedDateTimeLocalDateTime

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

推荐