英文:
DateTimeParseException - Text '8/19/2020' could not be parsed at index 0
问题
public static boolean isWeekStartFormatValid(String value) {
value = Util.getTrimmedValue(value);
//In constants public static final String DATE_FORMAT = "MM/dd/yyyy";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Constants.DATE_FORMAT);
LocalDate currentDate = LocalDate.now();
LocalDate inputDate = LocalDate.parse(value, formatter);
if(inputDate.isAfter(currentDate) && inputDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
return true;
}
return false;
}
当我输入值为 8/19/2020 时,出现以下错误:
[err] Caused by: java.time.format.DateTimeParseException: Text '8/19/2020' could not be parsed at index 0
[err] at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
[err] at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
[err] at java.time.LocalDate.parse(LocalDate.java:400)
我做错了什么?是否应该为这种情况添加 try catch?不确定该怎么做。欢迎任何建议。
英文:
Currently I have a method that is looking at the current date and comparing to an input date. I'm using the java.time API. I'm getting a DateTimeParseException where I am unable to parse the text value at index 0. Below is my code thus far:
public static boolean isWeekStartFormatValid(String value) {
value = Util.getTrimmedValue(value);
//In constants public static final String DATE_FORMAT = "MM/dd/yyyy";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Constants.DATE_FORMAT);
LocalDate currentDate = LocalDate.now();
LocalDate inputDate = LocalDate.parse(value, formatter);
if(inputDate.isAfter(currentDate) && inputDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
return true;
}
return false;
}
When I have the input value of 8/19/2020, I get the error below:
[err] Caused by: java.time.format.DateTimeParseException: Text '8/19/2020' could not be parsed at index 0
[err] at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
[err] at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
[err] at java.time.LocalDate.parse(LocalDate.java:400)
Is there something I'm not doing right? Should there be a try catch for something like this? Not sure what to do. Any suggestions appreciated.
答案1
得分: 2
使用java.time从字符串中获取日期:
LocalDate inputDate = LocalDate.parse(value, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
LocalDate currentDate = LocalDate.now();
检查输入日期是否在当前日期之后:
inputDate.isAfter(currentDate);
检查输入日期是否为星期六:
inputDate.getDayOfWeek() == DayOfWeek.SATURDAY;
英文:
Use java.time to get date from string:
LocalDate inputDate = LocalDate.parse(value,DateTimeFormatter.ofPattern("MM/dd/yyyy"));
LocalDate currentDate = LocalDate.now();
Check if input date is after current date:
inputDate.isAfter(currentDate)
Check if input date is Saturday:
inputDate.getDayOfWeek() == DayOfWeek.SATURDAY
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论