[英]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
),但出現錯誤:
線程“main”中的異常 java.time.format.DateTimeParseException:無法在 java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) 處的索引 0 處解析文本 'MAY 1 2013' .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);
}
正如parseCaseSensitive()
方法的文檔所說:
由於默認值區分大小寫,因此該方法只能在先前調用 #parseCaseInsensitive 之后使用。
將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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.