更新时间:2023-01-17 08:16:47
DateTimeFormatter
默认情况下是严格且区分大小写的。使用 DateTimeFormatterBuilder
并指定 parseCaseInsensitive()
来解析不区分大小写。
DateTimeFormatter
s are strict and case sensitive by default. Use a DateTimeFormatterBuilder
and specify parseCaseInsensitive()
to parse case insensitive.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("yy-MMM-dd")
.toFormatter(Locale.US);
能够解析数字月份(即15-01- 12
),你还需要指定 parseLenient()
。
To be able to parse numeric months (ie. "15-01-12"
), you also need to specify parseLenient()
.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.parseLenient()
.appendPattern("yy-MMM-dd")
.toFormatter(Locale.US);
您还可以更详细地将月份部分指定为不区分大小写/宽松:
You can also be more verbose to specify only the month part as case insensitive/lenient:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yy-")
.parseCaseInsensitive()
.parseLenient()
.appendPattern("MMM")
.parseStrict()
.parseCaseSensitive()
.appendPattern("-dd")
.toFormatter(Locale.US);
从理论上讲,这可能会更快,但我不确定是不是。
In theory, this could be faster, but I'm not sure if it is.
PS:如果在年份部分之前指定 parseLenient()
,它还将解析4位数年份(即2015-JAN-12
)正确。
PS: If you specify parseLenient()
before the year part, it will also parse 4 digit years (ie. "2015-JAN-12"
) correctly.