【问题标题】:How to handle upper or lower case in JSR 310? [duplicate]如何在 JSR 310 中处理大写或小写? [复制]
【发布时间】:2015-04-03 18:46:55
【问题描述】:

如果月份是大写或小写,即不是标题大小写,则 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);
    }
}

打印

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

【问题讨论】:

    标签: java java-8 java-time


    【解决方案1】:

    DateTimeFormatters 默认情况下是严格且区分大小写的。使用DateTimeFormatterBuilder 并指定parseCaseInsensitive() 以解析不区分大小写。

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

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

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

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

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

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

    PS:如果你在年份部分之前指定parseLenient(),它也会正确解析4位年份(即"2015-JAN-12")。

    【讨论】:

    • @hraldK 如果未设置.parseLenient(),格式“15-01-12”将失败。
    猜你喜欢
    • 2020-04-23
    • 2020-03-30
    • 2023-04-07
    • 1970-01-01
    • 2016-04-13
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    相关资源
    最近更新 更多