如何使DateTime-Pattern中的前导零成为可选

时间:2019-08-07 11:54:27

标签: java

我有一个用户输入字段,想解析他的日期,不管他输入什么。

用户可能会为其日期提供前导零或不带前导零,因此我想解析这样的输入

02.05.2019

还有这个

2.5.2019

但是据我所知,没有办法使前导零为可选,要么总是有2位数字,例如01、03、12等,或者只有必要的数字位例如1、3、12。< / p>

显然,我必须决定是否允许前导零,但是是否真的没有办法使前导零成为可选?


好吧,我测试了一个包含前导零dd.MM.uuuu的模式,并且测试了一个不包含前导零dMuuuu的模式,并且当我解析了错误的输入并抛出了错误的模式异常时。

因此,我的问题是是否有办法使前导零为可选。

3 个答案:

答案 0 :(得分:5)

当您知道时,这是微不足道的。一个图案字母,例如dM,将接受一个或两个数字(或最多9个数字的年份)。

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

输出:

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

我在文档中搜索了此信息,但并没有立即找到它。我认为没有充分的记录。

答案 1 :(得分:2)

您可以使用这样的自定义格式创建DateTimeFormatter

DateTimeFormatter.ofPattern("d.M.yyyy")

然后,您可以分析日期和日期,如果它们提供1或2位数字。

String input = "02.5.2019";
LocalDate date = LocalDate.parse(input, DateTimeFormatter.ofPattern("d.M.yyyy"));

我在这里使用了新的java.time包中的LocalDate,因此我假设您的Java版本是最新的。

答案 2 :(得分:0)

您建议的日期格式应该可以正常工作-就像该测试一样:

@Test
public void test() throws ParseException {
    SimpleDateFormat f = new SimpleDateFormat("d.M.yyyy");
    f.parse("7.8.2019");
    f.parse("07.08.2019");
    f.parse("007.008.002019");
}

DateTimeFormatter在比较中将不接受年份的前导零,但日和月的前导零都不是问题:

@Test
public void test2() throws ParseException {
    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    DateTimeFormatter f = builder.appendPattern("d.M.yyyy").toFormatter();
    f.parse("7.8.2019");
    f.parse("07.08.2019");
    f.parse("007.008.2019");
}