'Convert String to LocalDate getting pattern from Locale

I've been struggling trying to migrate a String to Date parse from java.util.Date to java.time.LocalDate

For instance, I don't know what pattern the user's input String will have... but I do know the user's java.util.Locale, from which I currently get the pattern for the convertion using java.text.SimpleDateFormat#toLocalizedPattern

This works, using old java.util.Date

// "25/05/2022" , Locale es-ES
public Date stringToDate(String dateString, Locale locale) throws ParseException {
    DateFormat dtf = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    String pattern = ((SimpleDateFormat) dtf).toLocalizedPattern(); // d/M/yy

    return dtf.parse(dateString); // 2022/05/25
}

This doesn't work, using directly java.time.LocalDate, It ends up with a java.time.format.DateTimeParseException

// "25/05/2022" , Locale es-ES
public LocalDate stringToLocalDate(String dateString, Locale locale) throws DateTimeParseException {
    DateFormat dtf = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    String pattern = ((SimpleDateFormat) dtf).toLocalizedPattern(); // d/M/yy

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, locale);

    return LocalDate.parse(dateString, formatter); 
// Exception in thread "main" java.time.format.DateTimeParseException: Text '25/05/2022' could not be parsed, unparsed text found at index 8
}

I know I could do the convertion like this, converting the old java.util.Date class to the new java.time.LocalDate class, But the goal is to stop relying on java.util.Date

LocalDate locDate = LocalDate.ofInstant(date.toInstant(), ZoneOffset.UTC);

What would the correct conversion to LocalDate look like since I don't know the pattern of the date?

The current problem with converting to Date this way is that if the user enters, for example, 13/05/2022, in MM/dd/yyyy format, Java converts it to 01/05/2023. I'd rather have a handled Exception in this scenario.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source