2016-08-24 21 views
3

表達爲什麼不能OffsetDateTime解析 '2016-08-24T18:38:05.507 + 0000' 中的Java 8

OffsetDateTime.parse("2016-08-24T18:38:05.507+0000")

導致以下錯誤:

java.time.format.DateTimeParseException: Text '2016-08-24T18:38:05.507+0000' could not be parsed at index 23

在另一方面,如預期

OffsetDateTime.parse("2016-08-24T18:38:05.507+00:00")

作品。

DateTimeFormatter's doc page提到不帶冒號的區域偏移作爲示例。我究竟做錯了什麼?我寧願不修改我的日期字符串來安撫Java。

+0

在此期間,我使用'OffsetDateTime.parse(dateString.replaceFirst(「\\ +(\\ d {2})(\\ d {2} )「,」+ $ 1:$ 2「))' –

+0

也許這與[OpenJDK bug#JDK-8074406](https://bugs.openjdk.java.net/browse/JDK-8074406)有關?在Java 9中修復了幾個格式化程序相關的錯誤。 –

回答

2

您正在調用以下方法。

public static OffsetDateTime parse(CharSequence text) { 
    return parse(text, DateTimeFormatter.ISO_OFFSET_DATE_TIME); 
} 

它使用用途DateTimeFormatter.ISO_OFFSET_DATE_TIMEDateTimeFormatter其中,作爲javadoc指出,執行以下操作:

The ISO date-time formatter that formats or parses a date-time with an offset, such as '2011-12-03T10:15:30+01:00'.

如果要分析日期有不同的格式,如2016-08-24T18:38:05.507+0000你應該使用OffsetDateTime#parse(CharSequence, DateTimeFormatter) 。下面的代碼應該可以解決你的問題:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
OffsetDateTime.parse("2016-08-24T18:38:05.507+0000", formatter); 
1

默認格式預計將與該區域的下列值偏移定義DateTimeFormatter.ISO_OFFSET_DATE_TIME

static final OffsetIdPrinterParser INSTANCE_ID_Z = new OffsetIdPrinterParser("+HH:MM:ss", "Z"); 
1

雖然DateTimeFormatter的模式語言不提供對未能滿足您的NO-區偏移代碼冒號形式,這並不意味着處理區域偏移量的預定義實例接受無冒號形式。 OffsetDateTime.parse()的one-arg版本指定它使用DateTimeFormatter.ISO_OFFSET_DATE_TIME作爲其格式化程序,並且格式化程序的文檔指定它支持三種格式,如the docs of ZoneOffset.getId()中所述。這些格式(均來自ISO-8601)都不符合您的非冒號格式。

但不用擔心:只需使用OffsetDateTime.parse()的兩個參數,即可提供合適的格式化程序。這有點不方便,但相當可行。

相關問題