Java LocalDate-解析区分大小写
我想知道,从年初到某个日期的天数是否是奇数。我尝试使用LocalDate解析字符串中的日期(Java LocalDate-解析区分大小写,java,java-8,java-time,date-parsing,localdate,Java,Java 8,Java Time,Date Parsing,Localdate,我想知道,从年初到某个日期的天数是否是奇数。我尝试使用LocalDate解析字符串中的日期(2013年5月1日),但出现错误: 线程“main”java.time.format.DateTimeParseException中的异常:无法在索引0处分析文本“2013年5月1日” 位于java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) 位于java.time.format.DateTimeFor
2013年5月1日
),但出现错误:
线程“main”java.time.format.DateTimeParseException中的异常:无法在索引0处分析文本“2013年5月1日”
位于java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
位于java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
位于com.javarush.task.task08.task0827.Solution.isDateOdd(Solution.java:23)
位于com.javarush.task.task08.task0827.Solution.main(Solution.java:16)
哪里有问题?将
MAY
修改为MAY
,并将1
修改为01
,这样就可以工作了。您的日常部分应该有两个数字,即2013年5月1日
然后,如果您确实希望传递大写月份名称,则应使用生成器和parseCaseSensitive()
总而言之:
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);
}
}
如果要将月份输入与所有大写字母一起使用,例如,
MAY
,则必须使用不区分大小写的DateTimeFormatter:
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);
}
}
正如parseCaseSensitive()
方法的开头所述:
由于默认值区分大小写,因此此方法只能在上一次调用#parseCaseSensitive后使用
2013年5月1日<代码>怎么样?刚刚尝试过这个,但仍然不起作用。MAY应该也是@nullpointerYes!问题出在我身上。非常感谢。因此,如果没有.parseCaseIntensitive,它将只对“1998年5月1日”有效,不是吗?不区分大小写意味着处理不受leter大小写的影响。因此,本月所有的大小写变化都会起作用:
mAy
、mAy
、mAy
、mAy
等等。@Aldres,您是对的,默认的区分大小写的解析只会被识别(大写M,小写ay)。
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);
}