Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 DateTimeFormatter parse date with both single digit and double digit day [duplicate]

I'm using DateTimeFormatter to parse a date:

private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate.parse("05/12/2015", parser); // it's ok
LocalDate.parse("5/12/2015", parser); // Exception

Unfortunately it doesn't parse correctly dates with a single day digit, like "5/12/2015".

I read some other post as this but the proposed solution doesn't work for me. I need a way to parse dates that can have single or double digits day.

like image 662
drenda Avatar asked Nov 12 '15 07:11

drenda


1 Answers

Just use d instead of dd - that still allows a leading 0, but doesn't require it. I suspect you'd want to do the same for months as well - it would be odd to have "1-or-2 digit" days but not months...

import java.time.*;
import java.time.format.*;

public class Test {
    public static void main(String[] args) throws Exception {
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("d/M/yyyy");
        System.out.println(LocalDate.parse("05/1/2015", parser));
        System.out.println(LocalDate.parse("05/01/2015", parser));
        System.out.println(LocalDate.parse("05/12/2015", parser));
        System.out.println(LocalDate.parse("5/12/2015", parser));
    }
}
like image 196
Jon Skeet Avatar answered Sep 27 '22 02:09

Jon Skeet