javadatejava-timedate-parsingdatetimeformatter

How can I make a leading zero in DateTime-Pattern optional


I have a user input field and would like to parse his date, whatever he puts in.

The user might provide his date with a leading zero or without one, so I wanna be able to parse an input like this

02.05.2019

and also this

2.5.2019

But as far as I can tell there is no way to make the leading zero optional, either always have 2 digits like 01, 03, 12 and so on, or only have the necessary digits like 1, 3, 12.

So apparently I have to decide whether to allow leading zeros or not, but is there seriously no way to make the leading zero optional ?


Well, I tested a pattern that included a leading zero dd.MM.uuuu and I tested a pattern that did not include a leading zero d.M.uuuu and when I parsed the wrong input with the wrong pattern exceptions were thrown.

Therefore my question is if there is a way to make the leading zero optional.


Solution

  • This is trivial when you know it. One pattern letter, for example d or M, will accept either one or two digits (or for year up to 9 digits).

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d.M.u");
        System.out.println(LocalDate.parse("02.05.2019", dateFormatter));
        System.out.println(LocalDate.parse("3.5.2019", dateFormatter));
        System.out.println(LocalDate.parse("4.05.2019", dateFormatter));
        System.out.println(LocalDate.parse("06.5.2019", dateFormatter));
        System.out.println(LocalDate.parse("15.12.2019", dateFormatter));
    

    Output:

    2019-05-02
    2019-05-03
    2019-05-04
    2019-05-06
    2019-12-15
    

    I searched for this information in the documentation and didn’t find it readily. I don’t think it is well documented.