LocalDate - 解析区分大小写

LocalDate - parsing is case sensitive

public class Solution {

    public static void main(String[] args) {
        System.out.println(isDateOdd("MAY 1 2013"));
    }

    public static boolean isDateOdd(String date) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy");
        formatter = formatter.withLocale(Locale.ENGLISH); 
        LocalDate outputDate = LocalDate.parse(date, formatter);
        return ((outputDate.getDayOfYear()%2!=0)?true:false);
    }
}

我想知道从年初到某个日期的天数是否为奇数。我尝试使用 LocalDate 从我的字符串 (MAY 1 2013) 中解析日期,但出现错误:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'MAY 1 2013' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.LocalDate.parse(LocalDate.java:400) at com.javarush.task.task08.task0827.Solution.isDateOdd(Solution.java:23) at com.javarush.task.task08.task0827.Solution.main(Solution.java:16)

哪里有问题?

MAY修改为May,将1修改为01即可。

您的日期部分应该有两位数,即 "MAY 01 2013" .

那么如果你真的想传递大写的月份名称,你应该使用构建器和 parseCaseInsensitive()

综合起来:

public static boolean isDateOdd(String date) {

    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    builder.parseCaseInsensitive();
    builder.appendPattern("MMM dd yyyy");
    DateTimeFormatter formatter = builder.toFormatter(Locale.ENGLISH); 

    LocalDate outputDate = LocalDate.parse(date, formatter);
    return ((outputDate.getDayOfYear()%2!=0)?true:false);
 }
}

如果您想使用所有大写字母的月份输入,例如MAY,您必须使用不区分大小写的 DateTimeFormatter:

public static boolean isDateOdd(String date) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("MMM d yyyy")
            .toFormatter(Locale.ENGLISH);
    LocalDate outputDate = LocalDate.parse(date, formatter);
    return (outputDate.getDayOfYear() % 2 != 0);
}

正如parseCaseSensitive()方法的documentation所说:

Since the default is case sensitive, this method should only be used after a previous call to #parseCaseInsensitive.