https://kotlinlang.org logo
Title
j

Jeff Jackson

05/11/2023, 2:10 PM
I'm trying to get the
DatePicker
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
        )
    }
}
d

dewildte

05/11/2023, 5:23 PM
I was having issues with this too. I select today but got millis back for tomorrow. I thought I was just not using it right or something.
s

Sean Proctor

05/11/2023, 5:55 PM
DatePicker
uses UTC. If you want to use the local timezone, you'll need to do some conversions when passing those values to
DatePicker
.
d

dewildte

05/11/2023, 5:56 PM
Pass input as UTC and then convert output to Local offset?
s

Sean Proctor

05/11/2023, 6:01 PM
To display the date, you should use UTC
Instant.ofEpochMilli(millis).atZone(ZoneId.of("UTC")).format(dateFormatter)
m

michaelv

05/15/2023, 4:57 AM
were you able to select the date from a UI test? when I tried it can’t see anything inside the date picker. Nothing showing up with the layout inspector.