I am trying to validate incoming date string and then convert it to a LocalDate. Here is my code:
public class DateTester {
public static void main(String[] args) {
System.out.println("converted date is" +stringToLD("2023-01-23"));
System.out.println("converted date is" +stringToLD("2023-13-21"));
System.out.println("converted date is" +stringToLD("2023-24-31"));
System.out.println("converted date is" +stringToLD("2023-36-34"));
// converted date is 2023-01-23
// converted date is2024-01-21
// converted date is2024-12-31
// converted date is2026-01-03
}
public static LocalDate stringToLD(String inputDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date;
try {
date = sdf.parse(inputDate);
} catch (ParseException e) {
throw new IllegalArgumentException("Unable to parse date, " + inputDate);
}
return LocalDate.parse(sdf.format(date));
}
}
but however when I send invalid date like 2023-13-21 I get back converted date as 2024-01-21 which is invalid and unwanted result. So I wanted to understand why this is happening and also looking for an alternate solution in java 8
Try it like this. Don't use Date or SimpleDateFormat. As stated by Ole V.V the default, strict, format is DateTimeFormatter.ISO_LOCAL_DATE
is used by LocalDate.parse()
.
That also matches your requirements.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public static LocalDate stringToLD(String inputDate) {
try {
return LocalDate.parse(inputDate);
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("Unable to parse date, " + inputDate);
}
}