DatePicker shows wrong value of month

Alok Kumar picture Alok Kumar · Dec 17, 2010 · Viewed 35.6k times · Source

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.

Answer

PearsonArtPhoto picture PearsonArtPhoto · Dec 17, 2010

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).