我在將字符串格式化為ZonedDateTime時遇到問題。我的客戶希望日期采用 ddMMyyhhmmss 等格式,沒有分隔符或類似的東西。這是我到目前為止所做的import java.time.format.DateTimeFormatter;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;public class MyClass { public static void main(String args[]) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyhhmmss"); String test = formatter .format(ZonedDateTime.now()).toString(); System.out.println(test); ZonedDateTime a = ZonedDateTime.parse(test,formatter); System.out.println(a.toString()); }}當它正確生成字符串時,錯誤發生在創建 LocalDateTime 變量的解析過程中28032019100707Exception in thread "main" java.time.format.DateTimeParseException: Text '28032019100707' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {MilliOfSecond=0, MinuteOfHour=7, HourOfAmPm=10, NanoOfSecond=0, MicroOfSecond=0, SecondOfMinute=7},ISO resolved to 2019-03-28 of type java.time.format.Parsed at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855) at java.time.ZonedDateTime.parse(ZonedDateTime.java:597) at MyClass.main(MyClass.java:14)在SO上搜索,我看到同一問題的一些答案建議使用LocalDateTime類作為中間類,然后解析為ZonedDateTime,但它仍然不起作用,拋出了相同的錯誤。我還嘗試使用此過程更改初始化DateTimeFormatter的方式DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("ddMMyyyyhhmmss") .toFormatter() .withZone(ZoneId.systemDefault());但它仍然不起作用。我知道我肯定錯過了一些愚蠢的東西,但我看不到什么。任何人都可以給我指出正確的方向嗎?
3 回答

明月笑刀無情
TA貢獻1828條經驗 獲得超4個贊
在您解析的字符串中,沒有關于時區的信息 - 那么格式化程序應該如何知道如何轉換為ZonedDateTime?
您需要在字符串中包含時區信息,或者使用另一個對象將其解析為沒有時區信息,然后將其傳輸到所需的區域中。
添加回答
舉報
0/150
提交
取消