DateTimeFormatter Support for Single Digit Day of Month and Month of Year

From the documentation:

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding.

So the format specifier you want is M/d/yyyy, using single letter forms. Of course, it will still parse date Strings like "12/30/1969" correctly as for these day/month values, two digits are the “minimum number of digits”.

The important difference is that MM and dd require zero padding, not that M and d can’t handle values greater than 9 (that would be a bit… unusual).


In Java 8 Date Time API, I recently used

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendOptional(DateTimeFormatter.ofPattern("M/dd/yyyy"))
            .toFormatter();

System.out.println(LocalDate.parse("10/22/2020", formatter));
System.out.println(LocalDate.parse("2/21/2020", formatter));

The best approach to deal with this kind of problem , That is number of different digits in Date (in day , month or year ) is to use this pattern : (M/d/[uuuu][uu]) .

Example:

String date = "7/7/2021"; // or "07/07/2021" or "07/7/21" etc
LocalDate localDate = LocalDate.parse(
date,DateTimeFormatter.ofPattern("M/d/[uuuu][uu]"));

Here uuuu/uu handle four and two digits year.