【发布时间】:2019-10-21 20:07:28
【问题描述】:
以下代码抛出 DateTimeParseException:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime dt = ZonedDateTime.parse(
"2019-01-01",
formatter.withZone(ZoneId.of("UTC"))
)
它也会抛出一个异常
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZonedDateTime dt = ZonedDateTime.parse(
"2019-01-01",
formatter)
)
一样
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
ZonedDateTime dt = ZonedDateTime.parse(
"2019-01-01",
formatter)
)
SimpleDateFormat 解析器工作得很好,但我正在讨论使用它,即使它不是线程安全的并且(我相信?)计划被弃用。
显然我更喜欢使用 java.time API,但即使按照在线记录的示例,我也无法让这个东西工作。我该怎么办?
【问题讨论】:
-
我怀疑
ZonedDateTime也需要时间部分, -
ZonedDateTime dt = LocalDate.parse("2019-01-01", formatter).atTime(LocalTime.of(0,0,0)).atZone(ZoneId.of("UTC")) -
你为什么认为你想要
ZonedDateTime?对于日期使用LocalDate。对于 UTC 的日期和时间,请使用Instant,或者如果您坚持使用OffsetDateTime。
标签: java datetime-format java-time