Java DateTimeFormatterBuilder with optional pattern results in DateTimeParseException

前端 未结 4 1361
傲寒
傲寒 2021-01-19 13:30

Goal

Provide a flexible parser for LocalDate instances that can handle input in one of the following formats:

  • yyyy
  • yyyyMM
  • yyyyMMdd<
4条回答
  •  悲&欢浪女
    2021-01-19 14:24

    Here is the solution. You can define possible patterns inside appendPattern(). And to optional put defaults.

       DateTimeFormatter parser = new DateTimeFormatterBuilder()
                .appendPattern("[yyyy][yyyyMM][yyyyMMdd]")
                .optionalStart()
                  .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
                  .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                .optionalEnd()
                .toFormatter();
        System.out.println(parser.parse("2014",LocalDate::from)); // Works
        System.out.println(parser.parse("201411",LocalDate::from)); // Works
        System.out.println(parser.parse("20141102",LocalDate::from)); // Works
    

    The output is

    2014-01-01
    2014-11-01
    2014-11-02
    

提交回复
热议问题