gpt4 book ai didi

java - LocalDate - 解析区分大小写

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:44:46 24 4
gpt4 key购买 nike

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 0at 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com