0

在 groovyConsole 中使用 DateTimeFormatter 和 DateTimeFormatterBuilder

String inputDateString = "31.2.58" // german date format

dtfIn = DateTimeFormatter
        .ofPattern ( "d.M.uu" )
        .withResolverStyle ( ResolverStyle.STRICT )

dtfIn.parse(inputDateString) // ERROR as expected

...但

// with base range 1937-2034
dtfIn = new DateTimeFormatterBuilder()
       .appendPattern("d.M.")
       .appendValueReduced(ChronoField.YEAR, 2, 2, Year.now().getValue() - 80)
       .parseStrict()
       .toFormatter()

dtfIn.parse(inputDateString) // Result: 1958-02-28

因此,带有 .parseStrict() 的 DateTimeFormatterBuilder 会解析相当智能,而 DateTimeFormatterBuilder 根本不应该这样做,但 STRICT 或 LENIENT (?)'

如果天数超过 31,我会收到错误消息。

问题似乎是 .appendValueReduced()。没有它,我会像预期的那样成为错误。

我做错了什么?

谢谢

拉维

4

1 回答 1

2

DateTimeFormatterfromDateTimeFormatterBuilder.toFormatter()确实是 SMART记录的:

解析器样式将是 SMART

要获得 STRICT,必须DateFormatter.withResolverStyle(ResolverStyle) 在这种情况下使用如下:

.toFormatter().withResolverStyle(ResolverStyle.STRICT);
于 2017-11-23T19:46:57.533 回答