[英]How to get month from Material design Datepicker Android kotlin
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.所以它显示了,但我无法从中获取数据。
For Java 8, you can use Date/Time API对于 Java 8,您可以使用日期/时间 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
否则,您可以使用
SimpleDateFormatter
binding.DatepickerButton.addOnPositiveButtonClickListener {
val calendar = Calendar.getInstance()
val simpleDateFormatter = SimpleDateFormat("MM", Locale.getDefault())
calendar.time = Date(it)
val month = simpleDateFormatter.format(calendar.time)
}
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.