DateTimeFormatter 将 LocalDate.of(0,1,5) 解析为“010105”是什么?
What does DateTimeFormatter parse LocalDate.of(0,1,5) to "010105"?
当使用格式 "yyMMdd"
的 DateTimeFormatter
时,奇怪的事情发生了... LocaleDate.of(0,1,5)
被格式化为 "010105"
,但“000105”被正确解析为 LocalDate.of(2015, 1, 5)
。这是为什么??
用于测试:
@Test
public void testYear2000() {
LocalDate localDate = LocalDate.of(0, 1, 5);
String format = DateTimeFormatter.ofPattern("yyMMdd").format(localDate);
assertThat(format, is("000105")); // fail! it is "010105"
LocalDate parse = LocalDate.parse("000105", DateTimeFormatter.ofPattern("yyMMdd"));
assertThat(parse, is(LocalDate.of(2000, 1, 5))); //pass
}
您的困惑来自以下事实:
LocalDate.of(0, 1, 5);
您指定了零年,即 2000 年之前的千年:
LocalDate.of(2000, 1, 5);
最后会输出000105
.
更新: @Meno Hochschild 添加了进一步的解释,我也会 link 好问题以供参考。
我对@Lachezar Balev 的正确答案进行了补充说明。按模式 yy 打印 0 年(两千多年前)意味着:使用 等同于 proleptic gregorian 0 年的两位数形式的纪元,即公元前 1 年 .因此,您会在格式化输出 010105 中看到第 1 年。
如果您使用了模式 uuMMdd(u=公历年份),那么输出确实符合您的预期 000105,但由于输入错误,从根本上来说仍然是错误的。
当使用格式 "yyMMdd"
的 DateTimeFormatter
时,奇怪的事情发生了... LocaleDate.of(0,1,5)
被格式化为 "010105"
,但“000105”被正确解析为 LocalDate.of(2015, 1, 5)
。这是为什么??
用于测试:
@Test
public void testYear2000() {
LocalDate localDate = LocalDate.of(0, 1, 5);
String format = DateTimeFormatter.ofPattern("yyMMdd").format(localDate);
assertThat(format, is("000105")); // fail! it is "010105"
LocalDate parse = LocalDate.parse("000105", DateTimeFormatter.ofPattern("yyMMdd"));
assertThat(parse, is(LocalDate.of(2000, 1, 5))); //pass
}
您的困惑来自以下事实:
LocalDate.of(0, 1, 5);
您指定了零年,即 2000 年之前的千年:
LocalDate.of(2000, 1, 5);
最后会输出000105
.
更新: @Meno Hochschild 添加了进一步的解释,我也会 link
我对@Lachezar Balev 的正确答案进行了补充说明。按模式 yy 打印 0 年(两千多年前)意味着:使用 等同于 proleptic gregorian 0 年的两位数形式的纪元,即公元前 1 年 .因此,您会在格式化输出 010105 中看到第 1 年。
如果您使用了模式 uuMMdd(u=公历年份),那么输出确实符合您的预期 000105,但由于输入错误,从根本上来说仍然是错误的。