简体   繁体   中英

ThreeTenABP: How to validate date using a custom date format / DateTimeFormatter?

I'm using ThreeTenABP and seem to have run into a difference of implementation between LocalDate.parse(String) and LocalDate.parse(String, DateTimeFormatter).

LocalDate.parse("31/02/1985", DateTimeFormatter.ofPattern("dd/MM/yyyy"))

Parses to "1985-02-28" without throwing an exception.

LocalDate.parse("2015-02-31")

DateTimeParseException: Text '2015-02-31' could not be parsed: Invalid date 'FEBRUARY 31'

The documentation almost implies this with "The string must represent a valid date" only mentioned with the formatter-less method.

How can I validate a date in a custom format like 31/02/1985 using threeten bp?

The main difference can be explained by the fact that the ISO_LOCAL_DATE-formatter is strict by default. Other formatters are smart by default. The full sentence you cited reads like this:

The string must represent a valid date and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.

So it is pretty clear that the formatter-less method can only parse ISO-compatible dates in strict mode, and even then only a subset of ISO-8601 , namely:

uuuu-MM-dd or uuuuMMdd

About the strict mode, you can see it studying the source code :

   public static final DateTimeFormatter ISO_LOCAL_DATE; 
   static { 
     ISO_LOCAL_DATE = new DateTimeFormatterBuilder() 
       .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD) 
       .appendLiteral('-') 
       .appendValue(MONTH_OF_YEAR, 2) 
       .appendLiteral('-') 
       .appendValue(DAY_OF_MONTH, 2) 
       .toFormatter(ResolverStyle.STRICT).withChronology(IsoChronology.INSTANCE); 
     } 

However, the strict mode does not seem to be well documented. Anyway, if you want to realize the strict mode with a custom formatter then simply call its method withResolverStyle(ResolverStyle.STRICT) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM