首頁  >  文章  >  LocalDate.parse 與 ResolverStyle.STRICT,對於亞洲/香港,返回意外結果

LocalDate.parse 與 ResolverStyle.STRICT,對於亞洲/香港,返回意外結果

王林
王林轉載
2024-02-13 20:54:071147瀏覽

php小編小新在本文中將介紹關於Java中的LocalDate.parse和ResolverStyle.STRICT的問題。在亞洲或香港使用這些方法時,可能會得到意外的結果。我們將探討這個問題,並提供解決方案。

問題內容

我的輸入是 19.12.0009,預期為 dec 19 00:00:00 hkt 9,但回傳結果為 dec 21 00:23:18 hkt 9,為什麼? 程式碼如下:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.uuuu")
                        .withResolverStyle(ResolverStyle.STRICT);
LocalDate localDate = LocalDate.parse("19.12.0009", formatter);
Instant instant = Instant.from(localDate.atStartOfDay(ZoneId.of("Asia/Hong_Kong")));
Date resultDate = Date.from(instant);
System.out.println("resultDate" + resultDate);

解決方法

zonerules 有一個轉換的概念,裡面有 savingslocaltransitions。我發現由於某種原因(可能是歷史原因), "asia/hong_kong" 本地轉換中的節省從 1904-10-30t00:36:42 開始。 resolverstyle.strict 不是這裡的問題!

這就是您看到 00:23:18 hkt 9 的原因。

如果您更改程式碼,例如:

localdate localdate = localdate.parse("19.12.1904", formatter);

預期輸出:

resultDate Mon Dec 19 01:00:00 JST 1904

以上是LocalDate.parse 與 ResolverStyle.STRICT,對於亞洲/香港,返回意外結果的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除