From DateTimeFormatter
javadoc:
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.
From what I understand, if the pad width is not exceeded and the count of letters is four, the minus sign (for negative years) should not be printed during formatting.
So I wrote such a snippet of code (figuring that I cannot use 'y
' because then the year will always be positive):
var negativeDate = LocalDate.now().minus(2021, ChronoUnit.YEARS);
var formatter = DateTimeFormatter.ofPattern("ppppuuuu");
var text = negativeDate.format(formatter);
System.out.println("formatted string: " + text);
This code throws DateTimeException
: "Cannot print as output of 5 characters exceeds pad width of 4".
So my question is basically how to see this last sentence from the javadoc work.
The Otherwise in the sentence you are asking about refers to the situation where the count of letters is 4 or greater. Confusingly the pad width here has nothing to do with pattern letter p
for padding. It refers to the number of digits to be printed. It refers back to the first sentence of the paragraph, The count of letters determines the minimum field width below which padding is used.
So to see that work, use 4 or more pattern letters and use a year that takes a greater number of digits than the number of pattern letters. It works with both u
, y
and Y
.
DateTimeFormatter uuuu = DateTimeFormatter.ofPattern("uuuu");
DateTimeFormatter yyyy = DateTimeFormatter.ofPattern("yyyy");
DateTimeFormatter uppercaseYyyy = DateTimeFormatter.ofPattern("YYYY");
LocalDate ld = LocalDate.of(12345, Month.OCTOBER, 23);
System.out.println(ld.format(uuuu));
System.out.println(ld.format(yyyy));
System.out.println(ld.format(uppercaseYyyy));
Output:
+12345 +12345 +12345
The minus sign is printed regardless of the number of characters to be printed. The documentation of SignStyle.EXCEEDS_PAD
says:
… A negative value will always output the '-' sign.
Documentation link: SignStyle.EXCEEDS_PAD