开发者

DatePicker shows wrong value of month

开发者 https://www.devze.com 2023-01-30 20:26 出处:网络
I have a problem in DatePicker in android when I use getMonth() method then it will return a wrong value.

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.


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


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


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.


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


You can use the following code:

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


if (month >= 0){
   month = month+1;
 }
 yourTextArea.setText(dayOfMonth+" / "+month+" / "+year);

It worked for me. Hope it would also work for you. Eat sleep code repeat

0

精彩评论

暂无评论...
验证码 换一张
取 消