【问题标题】:java.time.DateTimeException: Unable to extract ZoneId from temporaljava.time.DateTimeException:无法从时间中提取 ZoneId
【发布时间】:2020-04-19 05:05:42
【问题描述】:

当我运行第一段时,它非常好并生成输出。但在第二种情况下,当我运行此段 2 时,它会生成

DateTimeException : Unable to extract ZoneId from temporal.

第 1 段:

LocalDate ld = LocalDate.now();
System.out.println(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(ld));

第 2 段:

LocalDateTime ldt = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
System.out.println(dtf.format(ldt));

【问题讨论】:

标签: java datetime-format java-time


【解决方案1】:

我认为解释起来有点复杂,因为您在 ofLocalizedDateofLocalizedDateTimeFormatStyle 之间混合了两个东西:

在第一种情况下,您使用 FormatStyle.FULL 调用 ofLocalizedDate,因此您忽略了时间部分。

在第二种情况下,您还使用FormatStyle.FULL 调用ofLocalizedDateTime,这将包括日期的所有部分,LocalDateLocalDateTime 不是这种情况。

为了确保让我们尝试使用MEDIUMSHORT 而不是FULL

DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).format(ldt)
=> 30 déc. 2019 à 14:57:40 - without any exception 

欲了解更多详情,请查看此处的 cmets:

/**
 * Full text style, with the most detail.
 * For example, the format might be 'Tuesday, April 12, 1952 AD' or '3:30:42pm PST'.
 */
FULL,
/**
 * Long text style, with lots of detail.
 * For example, the format might be 'January 12, 1952'.
 */
LONG,
/**
 * Medium text style, with some detail.
 * For example, the format might be 'Jan 12, 1952'.
 */
MEDIUM,
/**
 * Short text style, typically numeric.
 * For example, the format might be '12.13.52' or '3:30pm'.
 */
SHORT;

要恢复,我们可以创建一个此表:

ofLocalizedTime ofLocalizedDate ofLocalizedDateTime
LocalTime MEDIUM, SHORT
LocalDate FULL, LONG, MEDIUM, SHORT
LocalDateTime MEDIUM, SHORT FULL, LONG, MEDIUM, SHORT MEDIUM, SHORT
ZonedDateTime FULL, LONG, MEDIUM, SHORT FULL, LONG, MEDIUM, SHORT FULL, LONG, MEDIUM, SHORT
OffsetDateTime MEDIUM, SHORT FULL, LONG, MEDIUM, SHORT MEDIUM, SHORT
=> FULL, LONG, MEDIUM, SHORT are FormatStyle

您可以将其阅读为LocalDateTime 可以使用ofLocalizedDate 和所有格式样式,并且不能接受任何FormatStyleofLocalizedDateTime

【讨论】:

  • 请详细解释为什么使用额外的思考 ZonedDateTime
  • @NgSharma 好的,现在检查我的答案,我想我让它更容易你清楚
【解决方案2】:

您混淆了“本地化”和“本地化”:

如您所见,它们是两个完全不同的术语。

现在,尝试提供 ZonedDateTime 值,这样您就可以了解它为什么需要 ZoneId

ZonedDateTime zdt = ZonedDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
System.out.println(dtf.format(zdt));

输出(语言环境:en_US,时区:America/New_York

Monday, December 30, 2019 at 8:09:16 AM Eastern Standard Time

如您所见,它需要时区才能知道时间是“东部标准时间”。

如果将时间样式从FULL 减少到MEDIUM,则不再需要时区。

LocalDateTime ldt = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.MEDIUM);
System.out.println(dtf.format(ldt));

输出

Monday, December 30, 2019, 8:09:16 AM

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2020-04-02
    • 2015-01-10
    • 2016-08-10
    • 1970-01-01
    相关资源
    最近更新 更多