我的代码中有模式“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。
如果您想从“基准年”开始,比如 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. [...]
关于Java8 appendPattern 与 appendValue 方法定义的模式产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38398078/