如何在JSR 310中处理大写或小写? [英] How to handle upper or lower case in JSR 310?
问题描述
如果一个月是UPPER或小写,即不是Title情况,则DateTimeFormatter无法解析日期。是否有一种简单的方法将日期转换为标题案例,或者使格式化程序更宽松的方法?
If a month is in UPPER or lower case, i.e. not Title case, DateTimeFormatter cannot parse the date. Is there a simple way to convert a date to title case, or a way to make the formatter more lenient?
for (String date : "15-JAN-12, 15-Jan-12, 15-jan-12, 15-01-12".split(", ")) {
try {
System.out.println(date + " => " + LocalDate.parse(date,
DateTimeFormatter.ofPattern("yy-MMM-dd")));
} catch (Exception e) {
System.out.println(date + " => " + e);
}
}
打印
15-JAN-12 => java.time.format.DateTimeParseException: Text '15-JAN-12' could not be parsed at index 3
15-Jan-12 => 2015-01-12
15-01-12 => java.time.format.DateTimeParseException: Text '15-01-12' could not be parsed at index 3
15-jan-12 => java.time.format.DateTimeParseException: Text '15-jan-12' could not be parsed at index 3
推荐答案
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.
这篇关于如何在JSR 310中处理大写或小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!