Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last digit of year with DateTimeFormatter

For year 2014 I want to display 4 and for 2029 -> 9

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

But I can't understand, how to do it with one last digit

DateTimeFormatter.ofPattern("yMMdd"); //returns 20151020. I want just 51020
like image 940
VextoR Avatar asked Oct 20 '15 13:10

VextoR


4 Answers

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).

like image 158
Tunaki Avatar answered Nov 14 '22 15:11

Tunaki


String sb = new SimpleDateFormat("yyMMdd").format(new Date());
        System.out.println(sb); // prints 151020
        sb = sb.substring(1, sb.length()); //remove 1st char
        System.out.println(sb); //prints 51020
like image 2
ΦXocę 웃 Пepeúpa ツ Avatar answered Nov 14 '22 13:11

ΦXocę 웃 Пepeúpa ツ


It's unlikely that DateTimeFormatter supports such an unusual requirement. If you have the year as an integral type, then use

year % 10

to extract the rightmost digit.

like image 1
Bathsheba Avatar answered Nov 14 '22 14:11

Bathsheba


That won't be possible with DateTimeFormatter. Check this link:

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

"y" formatter should throw year from 0 to 99

You simply should extract the last digit by yourself and create the string.

like image 1
fabrosell Avatar answered Nov 14 '22 13:11

fabrosell