Last digit of year with DateTimeFormatter
You can do it by building your own DateTimeFormatter
(and not relying on calculating substrings that can fail if your pattern evolves) like this:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendValueReduced(ChronoField.YEAR, 1, 1, 0)
.appendPattern("MMdd")
.toFormatter();
System.out.println(LocalDate.now().format(formatter)); // prints 51020
System.out.println(LocalDate.of(2029, 1, 1).format(formatter)); // prints 90101
However, this formatter can only be used to format a LocalDate
and can't be used to parse a LocalDate
.
appendValueReduced
is used to format a reduced value of a temporal field. In this case, we are appending a value of fixed width 1 and saying that the base value is 0 (this way, valid values will be between 0 and 9).