While writing unit tests for some date helpers i stumbled across a particular behaviour of DateTimeFormatter
that i would like to understand how to get around.
When outputting years >9999, it always adds a plus sign in front of the year number. Some quick code to illustrate this:
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"))
);
Now the docs states for year patterns that:
If the count of letters is less than four (but not two), then the sign is only output for negative years as per SignStyle.NORMAL. Otherwise, the sign is output if the pad width is exceeded, as per SignStyle.EXCEEDS_PAD.
So this gives a hint, but i'm still clueless about:
How to make DateTimeFormatter
output exactly the same string for Y10K+ dates that SimpleDateFormat.format()
does in my example (=unsigned for positive years >9999)?