Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 941
Robby Avatar asked Feb 23 '15 03:02

Robby


1 Answers

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);   
like image 176
Simon MᶜKenzie Avatar answered Oct 01 '22 03:10

Simon MᶜKenzie