在为某些日期助手编写单元测试时,我偶然发现了一种DateTimeFormatter
我想了解如何解决的特定行为。
当输出年份 >9999 时,它总是在年份数字前添加一个加号。一些快速代码来说明这一点:
LocalDate localDate = LocalDate.of(9999, 1, 1);
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(9999, 0, 1, 12, 0 , 0);
// following assertion passes as both strings are "01-01-9999"
Assertions.assertEquals(
new SimpleDateFormat("dd-MM-yyyy").format(cal.getTime()),
localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
);
localDate = localDate.plusDays(365);
cal.add(Calendar.DAY_OF_MONTH, 365);
// following assertion passes (lengthy workaround using SimpleDateFormat)
Assertions.assertEquals(
new SimpleDateFormat("dd-MM-yyyy").format(cal.getTime()),
new SimpleDateFormat("dd-MM-yyyy").format(Timestamp.valueOf(localDate.atTime(LocalTime.MIDNIGHT)))
);
// following assertion fails:
// Expected : "01-01-10000"
// Actual : "01-01-+10000"
Assertions.assertEquals(
new SimpleDateFormat("dd-MM-yyyy").format(cal.getTime()),
localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
);
现在,文档说明了年份模式:
如果字母数少于四个(但不是两个),则仅根据 SignStyle.NORMAL 输出负年份的符号。否则,如果超出焊盘宽度,则根据 SignStyle.EXCEEDS_PAD 输出符号。
所以这给出了一个提示,但我仍然一无所知:
如何使DateTimeFormatter
输出与我的示例中的 Y10K+ 日期完全相同的字符串SimpleDateFormat.format()
(= unsigned for positive years >9999)?