I am trying to set Date and Time for an event through the use of seperate date and time pickers for start and end times.
Start Date and Start Time End Date and End time
The code I have put together updates the date but Time is not changing
Can anybody guide with respect to the issue?
thanks
Code is below:
private val START_CAL_ID = 456
private lateinit var endCalendar: Calendar
private val END_CAL_ID = 678
private lateinit var endTimeCalendar: Calendar
private val calendar = Calendar.getInstance()
On Click date it shows Date picker and on click time it shows timepicker
private fun showCalendar(calendarId: Int) {
val datePicker = DatePickerDialog(
this,
R.style.DateTimePickerTheme,
{ datePicker: DatePicker, year: Int, month: Int, day: Int ->
if (calendarId == START_CAL_ID) {
startCalendar.set(year, month, day)
} else if (calendarId == END_CAL_ID) {
endCalendar.set(year, month, day)
}
updateDateFields()
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
)
datePicker.show()
}
private fun showTime(calendarId: Int) {
val timePickerDialog = TimePickerDialog(
this, R.style.DateTimePickerTheme,
{ view: TimePicker?, hourOfDay: Int, minute: Int ->
if (calendarId == START_CAL_ID) {
startCalendar.set(hourOfDay, minute)
} else if (calendarId == END_CAL_ID) {
endCalendar.set(hourOfDay, minute)
}
updateTimeFields()
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
false
)
timePickerDialog.show()
}
Updating the fields in the app to show the selected data in the right format
private fun updateDateFields() {
val formatter = SimpleDateFormat("MMM dd, yyyy", Locale.getDefault())
findViewById<TextView>(R.id.editEventStartDate).text = formatter.format(startCalendar.time)
findViewById<TextView>(R.id.editEventEndDate).text = formatter.format(endCalendar.time)
}
private fun updateTimeFields() {
val timeFormatter = SimpleDateFormat("hh.mm a", Locale.getDefault())
findViewById<TextView>(R.id.editEventStartTime).text =
timeFormatter.format(startCalendar.time)
findViewById<TextView>(R.id.editEventEndTime).text = timeFormatter.format(endCalendar.time)
}
set(int,int)
in Calendar
takes in the field id in its first argument and value in second. To set hour and minute, split it to two calls, e.g.
startCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
startCalendar.set(Calendar.MINUTE, minute)
(Also, consider using java.time APIs instead. They are much nicer to work with.)