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
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).
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With