Reputation: 681
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.
Upvotes: 56
Views: 43015
Reputation: 2315
This is the complete solution in Kotlin
private var mYear = 0
private var mMonth:Int = 0
private var mDay:Int = 0
private var updateDate: String = ""
Show Datepicker dialog
val c: Calendar = Calendar.getInstance();
mYear = c.get(Calendar.YEAR)
mMonth = c.get(Calendar.MONTH)
mDay = c.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = DatePickerDialog(
requireContext(),
OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
val date = SimpleDateFormat("dd/MM/yyyy").parse("$dayOfMonth/$monthOfYear/$year")
updateDate = "$dayOfMonth/${monthOfYear+1}/$year"
}, mYear, mMonth, mDay)
datePickerDialog.show()
Upvotes: 0
Reputation: 765
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😇
Upvotes: 0
Reputation: 4255
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);
Upvotes: 46
Reputation: 29
You can use the following code:
String mes = this.datepicker.getMonth()/10==0?("0"+this.datepicker.getMonth()):
String.valueOf(this.datepicker.getMonth());
Upvotes: 2
Reputation: 39748
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).
Upvotes: 86
Reputation: 1261
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.
Upvotes: 3