DatePicker shows wrong value of month

I have a problem in DatePicker in android when I use getMonth() method then it will return a wrong value.

For example:

DatePicker datepicker=new DatePicker();

int day=date.getDayOfMonth();
int month=date.getMonth();
int year=date.getYear();

t.setText(""+day+" / "+month+" / "+year);

If I will select aug 06 1987 then it will return 6/7/1987

I think it is an error, if not tell me the reason please.


Solution 1:

As described in the Android SDK, months are indexed starting at 0. This means August is month 8, or index 7, thus giving you the correct result.

It is a simple matter of adding 1 to the index returned by the API to get the traditional one-indexed month.

Although this behavior may seem strange, it is consistent with the java.util.Calendar class (although it is not consistent with joda.time.DateTime).

Solution 2:

In Android, when you select a date from the date picker, it starts counting the months from 0. So, this means that the returned month value is always month−1.

For example, if you select August (the 8th month), then it returns 8−1=7.

This means that what you need to do is add 1 to the month value that you get from the DatePicker.

You can do that this way:

DatePicker datepicker = new DatePicker();

int day   = date.getDayOfMonth();
int month = date.getMonth()+1;  // here I added 1 to the month
int year  = date.getYear();

t.setText(day+" / "+month+" / "+year);

Solution 3:

The reason I can think of why this has been in Java util is as follows:

Consider days from Jan 1st to Jan 31st.

A day like 22nd January can be considered as 0 month + 22 days of that year. Whereas 15th February can be stated as: 1 month + 15 days of that year.

Likewise 10th December can be stated as: 11 months + 10 days of that year.

Hence Jan-Dec is referred as 0-11.

Solution 4:

There is no error in this. Counting of months in the Calendar class is zero based. see this.

Solution 5:

You can use the following code:

String mes = this.datepicker.getMonth()/10==0?("0"+this.datepicker.getMonth()): 
String.valueOf(this.datepicker.getMonth());