使用 Locale 格式化 LocalDateTime 实例时获取

这对我来说不是很清楚。出于某种原因,当我尝试使用 格式化LocalDateTime实例DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withLocale(...)时,出现异常:


java.time.DateTimeException:无法提取值:类 java.time.LocalDateTime


例如,只有在我使用FormatStyle.LONG,时才会发生这种情况FormatStyle.MEDIUM。


这是我的测试:


@Test

public void dateTest() {

    LocalDateTime now = LocalDateTime.now();


    // this is ok. prints a value

    System.out.println("LocalDateTime now (formatted with locale): "

            + now.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)

                                                       .withLocale(new Locale("it"))));


    // this fails with java.time.DateTimeException: Unable to extract value: class java.time.LocalDateTime

    // only if FormatStyle.LONG (as it is now)

    System.out.println("LocalDateTime now (formatted with locale): "

            + now.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)

                                                       .withLocale(new Locale("it"))));

}

对此有什么好的解释吗?


慕虎7371278
浏览 233回答 2
2回答

湖上湖

FormatStyle.LONG你必须使用:ZonedDateTime.now()代替 :LocalDateTime.now()因为ZonedDateTime给了你很多细节,而不是像LocalDateTime.使用FormatStyle.LONG时,格式化程序会搜索其他信息,例如ZoneId其中未找到的信息LocalDateTime,因此您会遇到异常。

杨__羊羊

博士对此有什么好的解释吗?是的。LONGandFULL格式需要时区或与 UTC的偏移量。您LocalDateTime 缺少任何区域或偏移量。您的使用LocalDateTime.now不正确。Instant您应该只使用(或OffsetDateTime/ )捕捉当前时刻ZonedDateTime。Instant.now()  // Capture the current moment as seen in UTC.要更灵活地生成字符串,请使用OffsetDateTimeor ZonedDateTime。ZonedDateTime.now(     ZoneId.of( "Pacific/Auckland" )).format(    DateTimeFormatter.ofLocalizedDateTime(        FormatStyle.LONG   // Or `FULL`.    )    .withLocale( Locale.ITALY ) )新西兰时间 2019 年 3 月 6 日上午 10:22:23并且,与FormatStyle.FULL:新西兰夏令时间 2019 年 3 月 6 日,星期三 10:23:25 AMLocalDateTime不是片刻_LocalDateTime课程只是一个日期和一天中的时间。它故意缺少任何时区或与 UTC 偏移的概念。因此,根据定义,它不能代表片刻。从不打电话LocalDateTime.now()LocalDateTime.now();永远不要这样做,永远不要打电话now。LocalDateTime我想不出任何实际情况会要求这样做。LocalDateTime跟踪时刻时切勿使用。ALocalDateTime只是日期和时间,仅此而已。如果没有时区或从 UTC 偏移的上下文, aLocalDateTime不能代表时刻。它代表了大约 26-27 小时范围内的潜在时刻,即全球当前的时区范围。ALocalDateTime就像说“今年1月23日中午”。你是指日本东京的中午还是印度加尔各答的中午?或者也许是法国巴黎?蒙特利尔魁北克?这些不同地方的中午发生在不同的时刻,每个时刻都经过了几个小时。这里的“本地”是LocalDateTime指任何一个地方,或每个地方,但并不意味着任何特定的地方。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java