I implemented a DatePicker
in a fragment and when I pick a date from the Datepicker
dialog it returns the year and the day that I selected but I keep getting January in month.
I printed the value of monthOfYear
to see if it is changing and it gives the correct Int
for the month selected but when I set a static month like this cal.set(Calendar.MONTH, 5)
it gives same problem which means I guess something is wrong with setting the monthOfYear
in cal?
Anything I'm doing wrong?
val cal = Calendar.getInstance()
val dateSetListener = DatePickerDialog.OnDateSetListener {
view, year, monthOfYear, dayOfMonth ->
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, monthOfYear)
cal.set(Calendar.DAY_OF_YEAR, dayOfMonth)
val format = "dd.MM.yyyy"
val sdf = SimpleDateFormat(format,Locale.US)
binding.test.text = sdf.format(cal.time)
viewModel.updateDate(cal.timeInMillis)
}
binding.date.setOnClickListener {
DatePickerDialog(
requireContext(),
R.style.ThemeOverlay_App_DatePicker,
dateSetListener,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
).show()
}
CodePudding user response:
You are passing the day of month as the DAY_OF_YEAR, so it is overriding the month you set. But I agree with the above comment. Use LocalDate instead of Calendar.
Calendar, Date, TimeZone, and other java.util
date-time related classes are considered obsolete. Unfortunately, DatePicker predates availability of the java.time
classes like LocalDate, so it may be easiest to use Calendar if you're just converting to UTC millis and back.