LocalDate异常错误

Ald*_*res 3 java date-parsing java-8 java-time localdate

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;


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

我想知道,如果从年初到某个日期过去的天数很奇怪.我尝试使用LocalDate来解析我的字符串中的日期(2013年5月1日),但是我收到错误:

线程"main"中的异常java.time.format.DateTimeParseException:无法在java.time.format的java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)的索引0处解析文本"MAY 1 2013"位于com.javarush.task.task08.task0827.Solution.isDateOdd(Solution.java:23)的java.time.LocalDate.parse(LocalDate.java:400)中的.DateTimeFormatter.parse(DateTimeFormatter.java:1851). javarush.task.task08.task0827.Solution.main(Solution.java:16)

哪里有问题?

Nik*_*las 6

如果你想使用所有大写字母的月份输入,例如.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);
}
Run Code Online (Sandbox Code Playgroud)

正如该方法的文档所述parseCaseSensitive():

由于默认值区分大小写,因此只应在先前调用#parseCaseInsensitive之后使用此方法.

  • 不区分大小写意味着处理不受外壳影响.所以这个月的所有案例变化都会起作用:`mAy`,`MAY`,`may`,`mAY`等...... (2认同)