2016-01-25 116 views
0

我使用ZonedDateTime與Java 8的DateTimeFormatter。當我嘗試解析我自己的模式時,它不識別並拋出異常。Java8- ZonedDateTime與DateTimeFormatter無法識別格式

String oraceDt = "1970-01-01 00:00:00.0"; 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); 
    ZonedDateTime dt = ZonedDateTime.parse(oraceDt, formatter); 

Exception in thread "main" java.time.format.DateTimeParseException: Text '1970-01-01 00:00:00.0' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 1970-01-01T00:00 of type java.time.format.Parsed 
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918) 
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853) 
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597) 
at com.timezone.Java8DsteTimes.testZonedDateTime(Java8DsteTimes.java:31) 
at com.timezone.Java8DsteTimes.main(Java8DsteTimes.java:11) 

產生的原因:java.time.DateTimeException:無法從TemporalAccessor獲得ZonedDateTime:{},ISO決心1970-01-01T00:00型java.time.format.Parsed

回答

6

好,您希望創建一個始終引用時區的ZonedDateDate,但您的輸入不包含此類信息,並且您還沒有指示格式化程序在輸入缺少區域時使用默認時區。有您的問題,有兩種解決方案:

  1. 指導解析器使用時區(這裏使用該系統TZ爲例)

    String oraceDt = "1970-01-01 00:00:00.0"; 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); 
    ZonedDateTime zdt = 
        ZonedDateTime.parse(oraceDt, formatter.withZone(ZoneId.systemDefault())); 
    System.out.println(zdt); // in my default zone => 1970-01-01T00:00+01:00[Europe/Berlin] 
    
  2. 使用不另一種結果類型需要一個時區(這裏LocalDateTime

    String oraceDt = "1970-01-01 00:00:00.0"; 
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); 
    LocalDateTime ldt = LocalDateTime.parse(oraceDt, formatter); 
    System.out.println(ldt); // 1970-01-01T00:00 
    
+0

感謝Meno ..我去選項1,因爲我需要通過時區。創建ZoneId對象並傳遞給它。 ZoneId zoneId = ZoneId.of(ZoneId.SHORT_IDS.get(「CST」)); – Venkat

相關問題