Last digit of the year with DateTimeFormatter

During the year 2014I want to display 4and for2029 -> 9

I know how to format 4 digits => yyyy, and two digits =>yy

But I canโ€™t figure out how to do this with the last digit

DateTimeFormatter.ofPattern("yMMdd"); //returns 20151020. I want just 51020
+4
source share
4 answers

It is not true that it DateTimeFormattersupports such an unusual requirement. If you have a year as an integral type, use

year % 10

to extract the rightmost digit.

0
source

, DateTimeFormatter ( , , ) :

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

LocalDate LocalDate.

appendValueReduced . 1 , 0 ( , 0 9).

+5
+1
String sb = new SimpleDateFormat("yMMdd").format(new Date());
        System.out.println(sb); // prints 151020
        sb = sb.substring(1, sb.length()); //remove 1st char
        System.out.println(sb); //prints 51020
0

Source: https://habr.com/ru/post/1612431/


All Articles