如何在 js-joda 中进行严格的 LocalDate 解析?

How to do strict LocalDate parsing in js-joda?

我正在尝试解析 LocalDate from a String using strict resolution in js-joda(版本 1.1.1)。我不想接受无效日期的输入,例如 2016-05-32。但是我就是不明白。

我的代码是:

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

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

和错误:

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

ResolverStyle.LENIENTResolverStyle.SMART 相同的代码在此模式下可以正常工作。

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

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

如何在 js-joda 中使用严格分辨率?

JS Demo

更新

然而 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

模式 "yyyy-MM-dd" 在 STRICT 模式下不完整,因为它不提供纪元。请改用模式 "uuuu-MM-dd"。

您可以简单地使用 LocalDate.parse 函数而不指定格式化程序。

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

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