I would like to parse LocalDate objects from various date strings. All strings already have the format dd-MM-yy or dd-MM-yyyy. In the first case the base year should be prepended with 19 instead of 20.
I have this code but I can't get it working. What am I doing wrong?
public static LocalDate parseDateString(String date) {
DateTimeFormatter optionalFullYearParser = java.time.format.DateTimeFormatter.ofPattern("[dd-MM-yy][dd-MM-yyyy]");
DateTimeFormatter parser = new DateTimeFormatterBuilder()
.appendOptional(optionalFullYearParser)
.appendValueReduced(ChronoField.YEAR, 2, 4, 1900)
.toFormatter(new Locale ("nl","NL"));
return java.time.LocalDate.parse(date,parser);
}
System.out.println(parseDateString("11-10-56").toString());
System.out.println(parseDateString("11-10-1956").toString());
System.out.println(parseDateString("08-05-51").toString());
When I run this code it throws an Exception:
java.time.format.DateTimeParseException: Text '11-10-56' could not be parsed at index 8 ...
Any help will be greatly appreciated!