Java 8 DateTimeFormatter解析可选部分 [英] Java 8 DateTimeFormatter parsing optional sections
问题描述
我需要将日期时间解析为两种不同格式的字符串:
I need to parse date-times as strings coming as two different formats:
- 19861221235959Z
- 1986-12-21T23:59:59Z
以下dateTimeFormatter模式可以正确解析第一种日期字符串
The following dateTimeFormatter pattern properly parses the first kind of date strings
DateTimeFormatter.ofPattern ("uuuuMMddHHmmss[,S][.S]X")
但第二个失败,因为破折号,冒号和T不在预期范围内.
but fails on the second one as dashes, colons and T are not expected.
我试图使用可选部分,如下所示:
My attempt was to use optional sections as follows:
DateTimeFormatter.ofPattern ("uuuu[-]MM[-]dd['T']HH[:]mm[:]ss[,S][.S]X")
出乎意料的是,这会解析第二种日期字符串(带破折号的日期字符串),而不是第一种日期字符串,并抛出一个
Unexpectedly, this parses the second kind of date strings (the one with dashes), but not the first kind, throwing a
java.time.format.DateTimeParseException: Text '19861221235959Z' could not be parsed at index 0
好像可选部分没有被评估为可选...
It's as if optional sections are not being evaluated as optional...
推荐答案
正如Peter在评论中所述,问题在于您的模式将整个字符串视为年份.您可以使用.appendValue(ChronoField.YEAR, 4)
将其限制为四个字符:
As Peter stated in the comments, the problem is that your pattern is considering the entire string as the year. You can use .appendValue(ChronoField.YEAR, 4)
to limit it to four characters:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.appendPattern("[-]MM[-]dd['T']HH[:]mm[:]ss[,S][.S]X")
.toFormatter();
这可以正确解析您的两个示例.
This parses correctly with both of your examples.
如果您想变得更加冗长,可以这样做:
If you fancy being even more verbose, you could do:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.optionalStart().appendLiteral('-').optionalEnd()
.appendPattern("MM")
.optionalStart().appendLiteral('-').optionalEnd()
.appendPattern("dd")
.optionalStart().appendLiteral('T').optionalEnd()
.appendPattern("HH")
.optionalStart().appendLiteral(':').optionalEnd()
.appendPattern("mm")
.optionalStart().appendLiteral(':').optionalEnd()
.appendPattern("ss")
.optionalStart().appendPattern("X").optionalEnd()
.toFormatter();
这篇关于Java 8 DateTimeFormatter解析可选部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!