How to add Leading Zero using getMonth in Java (Android)

I use the int variable:

month = dp.getMonth() + 1; 

currently getting the output "2", and when I do the following:

 if (month<10){ month = '0'+month; }; 

I get: 50.

+6
source share
1 answer

Your problem is that your '0' char forced to an integer. Since '0' has an ASCII value of 48 , you get 48 + 2 = 50 .

Note that what you are trying to do will not work - you cannot add the leading 0 to month , since month is a number. The leading zero makes sense only in the lowercase representation of the number.

As explained in this answer , here's how to create a null number:

 String.format("%02d", month); 
+23
source

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


All Articles