Jeff Jackson
05/11/2023, 2:10 PMDatePicker
initial selection to work correctly in my time zone. Is there some way to tell the DatePicker
what time zone to use? It appears as though it is showing the date as UTC.
For example, if I set initialSelectedDateMillis
to be 1684540800000
the picker shows May 20, 2023
even though I'm in the Eastern Daylight timezone (UTC -4h).
Here's a simple example that reproduces the issue. The picker's title is a Text
that shows the current selection formatted for the system time zone.
@Composable
fun MainView(modifier: Modifier = Modifier) {
Scaffold {
var showDatePicker by remember { mutableStateOf(true) }
Text(
text = "Hello",
modifier = modifier.padding(it)
)
if (showDatePicker) {
// 1684540800000 milliseconds
// UTC: Sat May 20 2023 00:00:00
// Local: Fri May 19 2023 20:00:00
//
ShowDatePicker(initialSelectedDateMillis = 1684540800000) {
showDatePicker = false
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ShowDatePicker(initialSelectedDateMillis: Long, callback: () -> Unit) {
val datePickerState = rememberDatePickerState(
initialSelectedDateMillis = initialSelectedDateMillis
)
DatePickerDialog(
onDismissRequest = callback,
confirmButton = {},
) {
DatePicker(
state = datePickerState,
title = {
val dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
val millis = datePickerState.selectedDateMillis ?: 0L
Text(
text = Instant.ofEpochMilli(millis).atZone(TimeZone.getDefault().toZoneId()).format(dateFormatter),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(20.dp)
)
},
showModeToggle = false
)
}
}
dewildte
05/11/2023, 5:23 PMSean Proctor
05/11/2023, 5:55 PMDatePicker
uses UTC. If you want to use the local timezone, you'll need to do some conversions when passing those values to DatePicker
.dewildte
05/11/2023, 5:56 PMSean Proctor
05/11/2023, 6:01 PMInstant.ofEpochMilli(millis).atZone(ZoneId.of("UTC")).format(dateFormatter)
michaelv
05/15/2023, 4:57 AM