DateTimeParseException - Text '8/19/2020' could not be parsed at index 0

993 views Asked by At

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

There are 1 answers

2
Egor On

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