DateTimeFormatter pattern with liternal and no separator does not work

后端 未结 2 887
攒了一身酷
攒了一身酷 2021-01-18 02:36

The parser generated by DateTimeFormatter.ofPattern exhibits the following interesting behaviour which is preventing me from writing a pattern to parse a string

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 03:27

    There is a bug in the DateTimePrinterParser:

    I step debugged all the way through it, apparently you can not have digits as literals. Similar test codes proves this if you step debug all the way through to the DateTimeFormatterBuilder.parse() method you can see what it is doing wrong.

    Apparently the Value(YearOfEra,4,19,EXCEEDS_PAD) parser consumes the 00 where they stop if those are not digits because it is looking for a number 4 to 19 digits long. The DateTimeFormatter that is embedded in the DateTimeParseContext is wrong.

    If you put a non-digit character literal like xx it works, digit literals don't.

    Both of these fail:

    final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM'00'");
    System.out.println(sdf.parse("20150100"));
    

    Exception in thread "main" java.text.ParseException: Unparseable date: "20150100" at java.text.DateFormat.parse(DateFormat.java:366)

    final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMM'00'");
    System.out.println(dateTimeFormatter.parse("20150100", YearMonth::from));
    

    Exception in thread "main" java.time.format.DateTimeParseException: Text '20150100' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)

    Both of these succeed:

    final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM'xx'");
    System.out.println(sdf.parse("201501xx"));
    

    Thu Jan 01 00:00:00 EST 2015

    final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMM'xx'");
    System.out.println(dateTimeFormatter.parse("201501xx", YearMonth::from));
    

    2015-01

提交回复
热议问题