Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTimeFormatter single digit month

Tags:

java

date

I'm trying to parse a date where the month goes from 1 to 12 (And not from 01 to 12).

I'm trying this:

    System.out.println(DateTimeFormatter.ofPattern("[[MM][M]yyyy").parse("112019"));
    System.out.println(DateTimeFormatter.ofPattern("[[MM][M]yyyy").parse("82019"));

The first line works, the second fails.

Even Myyyy fails to parse the second line. I have not been able to find any pattern able to parse 82019 :(

[M][MM] as well as [MM][M] fail. Reading the documentation it says:

M/L month-of-year number/text 7; 07; Jul; July; J

So M is supposed to parse both 8 and 11.

Anyone has been able to get something working?

This works: System.out.println(DateTimeFormatter.ofPattern("M-yyyy").parse("8-2019")); But the data I got don't have any separation between the month and the year.

like image 766
jmspaggi Avatar asked Dec 19 '25 21:12

jmspaggi


1 Answers

Perhaps DateTimeFormatterBuilder is what you are looking for:

String s = "112019";
System.out.println(new DateTimeFormatterBuilder()
        .appendPattern("M")
        .appendValue(ChronoField.YEAR, 4)
        .toFormatter()
        .parse(s)
);
like image 184
Christian S. Avatar answered Dec 21 '25 11:12

Christian S.