Java8 appendPattern 与 appendValue 方法定义的模式产生不同的结果

Java8 appendPattern vs pattern defined by appendValue methods produces different result

我的代码中有模式 "ddMMyy" 我已经使用 appendValue 方法指定了它:

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                    .appendValue(ChronoField.DAY_OF_MONTH, 2)
                    .appendValue(ChronoField.MONTH_OF_YEAR, 2)
                    .appendValue(ChronoField.YEAR_OF_ERA, 2)
                    .toFormatter();
System.out.println(LocalDate.parse("100199", dateTimeFormatter));

但是这会产生年份“0099”:

0099-01-10

如果我将其更改为使用这样的 appendPattern:

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                    .appendPattern("ddMMyy")
                    .toFormatter();
System.out.println(LocalDate.parse("100199", dateTimeFormatter));

我得到了包含世纪的“2099”年的正确结果。

2099-01-10

代码对我来说似乎是等价的,为什么它不产生相同的结果?为什么在第一种情况下缺少世纪?

因为 appendValue 是在没有进一步操作的情况下传递的年份 - 在您的情况下是 99.

如果您想从 "base year" 开始,比如 2000 年,并将该值添加到该基准年(以获得 2099),您可以改用 appendValueReduced

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
        .appendValue(ChronoField.DAY_OF_MONTH, 2)
        .appendValue(ChronoField.MONTH_OF_YEAR, 2)
        .appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2, LocalDate.of(2000, 1, 1))
        .toFormatter();

当您使用 yy 模式时,默认情况下您会获得该行为,详见 the javadoc:

Year: The count of letters determines the minimum field width below which padding is used. If the count of letters is two, then a reduced two digit form is used. For printing, this outputs the rightmost two digits. For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive. [...]