0

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!

Ferry Kranenburg
  • 2,625
  • 1
  • 17
  • 23
  • 1
    You’re over-complicating it. See how simple it is in my answer to the linked original question. The trick is to have `yyyy` *before* `yy`, or it will parse the first two of the four digits as a two digit year and then get stuck. – Ole V.V. Nov 21 '18 at 22:11

1 Answers1

2

There is no need for 2 formatter objects to do this, and you shouldn't include the year part in the pattern text when you then use appendValueReduced to add the year part.

public static LocalDate parseDateString(String date) {
    DateTimeFormatter parser = new DateTimeFormatterBuilder()
            .appendPattern("dd-MM-")
            .appendValueReduced(ChronoField.YEAR, 2, 4, 1900)
            .toFormatter(Locale.forLanguageTag("nl-NL"));
    return java.time.LocalDate.parse(date, parser);
}

Test

System.out.println(parseDateString("11-10-56").toString());
System.out.println(parseDateString("11-10-1956").toString());
System.out.println(parseDateString("08-05-51").toString());

Output

1956-10-11
1956-10-11
1951-05-08
NiVeR
  • 9,644
  • 4
  • 30
  • 35
Andreas
  • 154,647
  • 11
  • 152
  • 247