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
,你必须使用不区分大小写的 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);
}
作为documentation parseCaseSensitive()
方法说:
Since the default is case sensitive, this method should only be used after a previous call to #parseCaseInsensitive.
关于java - LocalDate - 解析区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46486822/