DateTimeFormatter auto-corrects invalid (syntactically possible) calendar date

前端 未结 1 419
醉梦人生
醉梦人生 2020-12-21 08:46

Java DateTimeFormatter throws an exception for when you try a date that goes outside of a possible range, for example:

DateTimeFormatter dtf = D         


        
相关标签:
1条回答
  • 2020-12-21 08:59

    You can use a STRICT resolver style:

    import static java.time.format.ResolverStyle.STRICT;
    
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/uuuu").withResolverStyle(STRICT);
    

    By default, ofPattern uses a SMART resolver style which will use reasonable defaults.

    Note that I have used uuuu instead of yyyy, i.e. YEAR instead of YEAR_OF_ERA. Assuming you are in a Gregorian calendar system, the two are equivalent for years in the current era (year 1 or greater). The difference is explained in more details in the links above.

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