首页 > 解决方案 > java.time.DateTimeException:无法从时间中提取 ZoneId

问题描述

当我运行第一段时,它非常好并生成输出。但是在第二种情况下,当我运行此段 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));

标签: javadatetime-formatjava-time

解决方案


我认为解释起来有点复杂,因为您在两件事之间混合ofLocalizedDateofLocalizedDateTime并且FormatStyle

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

在第二种情况下,您还调用ofLocalizedDateTimewhichFormatStyle.FULL将包括日期的所有部分,而LocalDateor则不是这种情况LocalDateTime

可以肯定的是,让我们尝试使用MEDIUM,或SHORT代替FULL

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

有关更多详细信息,请查看此处的评论:

/**
 * 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;

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

本地化时间 ofLocalizedDate ofLocalizedDateTime
当地时间 中,短
本地日期 全、长、中、短
本地日期时间 中,短 全、长、中、短 中,短
分区日期时间 全、长、中、短 全、长、中、短 全、长、中、短
偏移日期时间 中,短 全、长、中、短 中,短
=> FULL, LONG, MEDIUM, SHORT are FormatStyle

您可以阅读它,因为它LocalDateTime可以ofLocalizedDate与所有格式样式一起使用,并且不能接受任何FormatStyleofLocalizedDateTime


推荐阅读