Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting months as 01,02 instead of 1,2

I am working with the Calender class and more specifically I need to get back all 12 months as two numbers.

If I use the following code:

 int month = (myCalendar.get(Calendar.MONTH)) +1;

This is what I get for the different months: 1,2,3,4,5,6,7,8,9,10,11,12

But what I really need is: 01,02,03,04,05,06,07,08,09,10,11,12

This is beacuse I need to make substrings and it will go wrong if the number of ints I get. Is there an easy way to fix this?

I could use an if statement and check if the whole date is just 5 numbers, then add a zero and the 3 position, but it feels cumberstone.

like image 609
Essej Avatar asked May 28 '16 13:05

Essej


2 Answers

If you don't want to try if statement try this

Date date = new Date();
String monthDateFormat = "MM";
SimpleDateFormat mdf = new SimpleDateFormat(monthDateFormat);
String month = mdf.format(date);
like image 62
BOUTERBIAT Oualid Avatar answered Oct 01 '22 00:10

BOUTERBIAT Oualid


The reason it is loading as "1" instead of "01" is because it is stored in an int, do the following if statement:

String sMonth = "";
if (month < 10) {
    sMonth = "0"+String.valueOf(month);
} else {
    sMonth = String.valueOf(month);
}

Then use sMonth instead of month.

like image 36
Jono Avatar answered Oct 01 '22 00:10

Jono