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

Robby picture Robby · Feb 23, 2015 · Viewed 21.2k times · Source

I'm using an int variable:

month = dp.getMonth() + 1;

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

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

I get: 50.

Answer

Simon MᶜKenzie picture Simon MᶜKenzie · Feb 23, 2015

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

Note that what you're trying to do won't work - you can't add a leading 0 to month, as month is a number. A leading zero only makes sense in a string representation of a number.

As explained in this answer, here's how to produce a zero-padded number:

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