如何在JSR 310中处理大写或小写?

Pet*_*rey 12 java java-8 java-time

如果一个月是UPPER或小写,即不是Title情况,则DateTimeFormatter无法解析日期.有一种简单的方法可以将日期转换为标题案例,还是一种使格式化程序更宽松的方法?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

版画

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
Run Code Online (Sandbox Code Playgroud)

har*_*ldK 25

DateTimeFormatter默认情况下,s是严格且区分大小写的.使用a DateTimeFormatterBuilder并指定parseCaseInsensitive()解析不区分大小写.

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .parseCaseInsensitive()
    .appendPattern("yy-MMM-dd")
    .toFormatter(Locale.US);
Run Code Online (Sandbox Code Playgroud)

为了能够解析数字月份(即."15-01-12"),您还需要指定parseLenient().

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .parseCaseInsensitive()
    .parseLenient()
    .appendPattern("yy-MMM-dd")
    .toFormatter(Locale.US);
Run Code Online (Sandbox Code Playgroud)

您还可以更详细地将月份部分指定为不区分大小写/宽松:

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

从理论上讲,这可能会更快,但我不确定是不是.

PS:如果您parseLenient()在年份部分之前指定,它还将"2015-JAN-12"正确解析4位数年份(即.).

  • @hraldK如果未设置`.parseLenient()`,格式"15-01-12"将失败. (2认同)