Issue with DateTimeParseException when using STRICT resolver style

后端 未结 2 605
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 13:59

I am trying to parse a date string using the following pattern: yyMMdd and the STRICT resolver as follows:

DateTimeFormatter format         


        
相关标签:
2条回答
  • 2020-12-06 14:28

    While JodaStephen has nicely explained the reason for the exception and given one good solution (use uu rather than yy), I am offering a couple of other possible solutions:

    1. The obvious one that you probably don’t want: leave the resolver style at SMART (the default). In other words either leave out .withResolverStyle(ResolverStyle.STRICT) completely or change it to .withResolverStyle(ResolverStyle.SMART).
    2. Provide a default era.

    For the second option here is a code example:

        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("yyMMdd")
                .parseDefaulting(ChronoField.ERA, 1)
                .toFormatter()
                .withResolverStyle(ResolverStyle.STRICT);
    
        String expiryDate = "160501";
        LocalDate result = LocalDate.parse(expiryDate, formatter);
        
        System.out.println(result);
    

    Output is:

    2016-05-01

    Where the last solution may make a difference compared to using uu in the format pattern:

    1. It allows us to use a format pattern that is given to us where we cannot control whether pattern letter u or y is used.
    2. With pattern letter y it will fail with an exception if the string contains a negative year. Depending on your situation and requirements this may be desirable or unacceptable.
    0 讨论(0)
  • 2020-12-06 14:29

    The strict resolver requires an era to go with YearOfEra. Change your pattern to use "u" instead of "y" and it will work, ie. "uuMMdd".

    0 讨论(0)
提交回复
热议问题