Java – how do I handle uppercase or lowercase in JSR 310?

There is already an answer to this question: > how to parse case insensitive strings with jsr310 datetimeformatter? two

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);
    }
}

print

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

Solution

By default, datetimeformatter is strictly case sensitive Use datetimeformatterbuilder and specify parsecasesensitive() to resolve case insensitive

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .parseCaseInsensitive()
    .appendPattern("yy-MMM-dd")
    .toFormatter(Locale.US);

In order to be able to parse digital months (i.e. "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 specify case insensitive / omitted month parts in more detail:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("yy-")
    .parseCaseInsensitive()
    .parseLenient()
    .appendPattern("MMM")
    .parseStrict()
    .parseCaseSensitive()
    .appendPattern("-dd")
    .toFormatter(Locale.US);

In theory, it may be faster, but I don't know if

PS: if parselenient () is specified before the year, it will also correctly parse the 4-digit year (i.e. "2015-jan-12")

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>