LocalDate exception error
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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); } } |
我想知道,如果从年初到某个日期过去的天数很奇怪。 我尝试使用LocalDate来解析我的字符串中的日期(2013年5月1日),但是我收到错误:
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)
哪里有问题?
如果要将月份的输入与所有大写字母(例如
1 2 3 4 5 6 7 8 |
正如
Since the default is case sensitive, this method should only be used after a previous call to #parseCaseInsensitive.
你的日期部分应该有两位数,即
然后,如果您确实想要传递大写月份名称,则应使用构建器和
把它们放在一起:
1 2 3 4 5 6 7 8 9 10 11 | 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); } } |
将