Java8 DateTimeFormatter 将日期解析为一位数和两位数的日期

Java8 DateTimeFormatter parse date with both single digit and double digit day

我正在使用 DateTimeFormatter 来解析日期:

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

不幸的是,它无法正确解析只有一天数字的日期,例如 "5/12/2015"

我读了一些其他 post 作为 this 但建议的解决方案对我不起作用。 我需要一种方法来解析可以有一位数或两位数天的日期。

只需使用 d 而不是 dd - 仍然允许前导 0,但不需要它。我怀疑你也想在几个月内做同样的事情 - 有“一位或两位数”的日子而不是几个月会很奇怪......

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));
    }
}