How to do strict LocalDate parsing in js-joda?

2k views Asked by At

I'm trying to parse a LocalDate from a String using strict resolution in js-joda (version 1.1.1). I don't want to accept inputs that aren't valid dates, like 2016-05-32. But I just don't get it.

My code is:

formatter = (new JSJoda.DateTimeFormatterBuilder)
    .appendPattern("yyyy-MM-dd")
    .toFormatter(JSJoda.ResolverStyle.STRICT);

JSJoda.LocalDate.parse("2016-05-10", formatter);

and the error:

Text '2016-05-10' could not be parsed: Unable to obtain LocalDate from
TemporalAccessor: [object Object], type DateTimeBuilder: 2016-05-10,
at index: 0

The same code with ResolverStyle.LENIENT or ResolverStyle.SMART works as it's expected for this modes.

formatter = (new JSJoda.DateTimeFormatterBuilder)
    .appendPattern("yyyy-MM-dd")
    .toFormatter(JSJoda.ResolverStyle.LENIENT);

JSJoda.LocalDate.parse("2016-05-32", formatter); // result 2016-06-01

How can I use strict resolution in js-joda?

JS Demo

Update:

However the js-joda DateTimeFormatter API does not mention this option, the pattern uuuu-MM-dd proposed by @JodaStephen works fine. Working Js Demo

js-joda api:

 |Symbol  |Meaning                     |Presentation      |Examples
 |--------|----------------------------|------------------|---------------
 | G      | era                        | number/text      | 1; 01; AD; Anno Domini
 | y      | year                       | year             | 2004; 04
 | D      | day-of-year                | number           | 189
 | M      | month-of-year              | number/text      | 7; 07; Jul; July; J

Java api:

 Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   G       era                         text              AD; Anno Domini; A
   u       year                        year              2004; 04
   y       year-of-era                 year              2004; 04
   D       day-of-year                 number            189
2

There are 2 answers

0
JodaStephen On BEST ANSWER

The pattern "yyyy-MM-dd" is incomplete in STRICT mode as it does not provide the era. Use the pattern "uuuu-MM-dd" instead.

0
pithu On

You might simply use the LocalDate.parse function without specifying a formatter.

LocalDate.parse('2016-05-10');  // '2016-05-10'

LocalDate.parse('2016-05-32');  // throws a DateTimeParseException