当前位置: 首页 > 面试题库 >

在Java8中使用时区格式化LocalDateTime

翁烨霖
2023-03-14
问题内容

我有这个简单的代码:

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)

如何解决这个问题?


问题答案:

LocalDateTime是没有时区的日期时间。您以格式指定了时区偏移格式符号,但是LocalDateTime没有此类信息。这就是为什么发生错误。

如果您需要时区信息,请使用ZonedDateTime

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


 类似资料:
  • 我有这个简单的代码: 然后我将得到以下异常: 如何解决这个问题?

  • 我正在将一个项目从Joda Time过渡到java8的本机时间库,我遇到了一个障碍。 我一直找不到持续时间的格式化程序。我想有一个自定义的字符串格式,例如HHH MM,其中75小时15分钟的持续时间将格式化为“75 15”。 通过转换为句点并使用句点Formatter,Joda-Time很容易做到这一点,但是我无法在Java8中找到这种类型的类。我错过了什么吗?

  • Java 8 添加了一个新的 java.time API 来处理日期和时间 (JSR 310)。 我有字符串形式的日期和时间(例如< code >“2014-04-08 12:30”)。如何从给定的字符串中获取< code>LocalDateTime实例? 在我完成对象的工作后:如何将实例转换回与上述格式相同的字符串?

  • 问题内容: 我正在使用Moment.js解析和格式化Web应用程序中的日期。作为JSON对象的一部分,我的后端服务器以UTC纪元(Unix偏移)为单位发送日期(以毫秒为单位)。 在特定时区中 解析日期很容易-只需在解析前将RFC 822时区标识符附加到字符串的末尾即可: 但是,如何格式化 特定时区中 的日期? 无论浏览器的当前时间如何,我都希望获得一致的结果,但是我不想以UTC显示日期。 问题答案

  • 问题内容: 我正在尝试使用这种格式来格式化当前时间。 输出: 有什么建议? 问题答案: 用 由于Go使用以下常量来格式化日期,请参阅此处