I have a datepicker from material design, its opening well in the app. Now how can i get for example the selected month from the datepicker.
Initialize the datepicker:
val datePicker = MaterialDatePicker.Builder.datePicker()
.setTitleText("Kies een datum")
.setSelection(MaterialDatePicker.todayInUtcMilliseconds())
.build()
On button hit the calendar opens:
fun pickDate() {
binding.DatepickerButton.setOnClickListener {
datePicker.show(activity?.supportFragmentManager!!, datePicker.toString())
}
}
so it shows, but i cannot get the data from it.
CodePudding user response:
For Java 8, you can use Date/Time API
binding.DatepickerButton.addOnPositiveButtonClickListener {
var dateFormatter = DateTimeFormatter.ofPattern("MM", Locale.getDefault())
val month = dateFormatter.format(
Instant.ofEpochMilli(it)
.atZone(ZoneId.systemDefault()).toLocalDate()
)
}
Otherwise, you can use SimpleDateFormatter
binding.DatepickerButton.addOnPositiveButtonClickListener {
val calendar = Calendar.getInstance()
val simpleDateFormatter = SimpleDateFormat("MM", Locale.getDefault())
calendar.time = Date(it)
val month = simpleDateFormatter.format(calendar.time)
}
CodePudding user response:
Try this click positive button click listener. after getting the date you can extract a month from it.
binding.DatepickerButton.addOnPositiveButtonClickListener {
val (startOfRange, endOfRange) = it // in case date range operation
val date = it // single select date
String dateString = DateFormat.format("dd/MM/yyyy", new Date(date)).toString();
}