Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 104 ยท Building a Real UI

Date and Time Pickers in Compose

Use Material 3 DatePicker, DatePickerDialog, TimePicker, TimeInput and DateRangePicker in Compose, and avoid the UTC milliseconds trap when converting to java.time.

Sooner or later a form needs a date: a birthday, a due date, a reminder at 7:30. You could give the user two text fields, but people make typos and formats differ around the world. Material 3 ships ready-made pickers for this, and Compose exposes them as composables: DatePicker, DatePickerDialog, TimePicker, TimeInput and DateRangePicker.

The pickers are easy to show and surprisingly easy to get wrong. The classic mistake is a date that is one day off, caused by the way the date picker stores its value. This lesson shows each picker, the state classes behind them, and how to convert results to java.time safely. The Android UI cannot run here, so the real Compose code is read-only; the TryIts are plain Kotlin stand-ins that reproduce the conversion rules and the time-picker model exactly, so you can see the numbers.

The Material 3 pickers are part of androidx.compose.material3, and some of them are still marked @ExperimentalMaterial3Api. You opt in with @OptIn(ExperimentalMaterial3Api::class) on the function that uses them. Check the release notes of your Material 3 version, because the experimental set shrinks over time.

The state classes

Each picker is driven by a state object that you create with a remember function. The state holds the selection; the composable only draws it.

Picker State Result
DatePicker rememberDatePickerState() selectedDateMillis: Long?
DateRangePicker rememberDateRangePickerState() selectedStartDateMillis, selectedEndDateMillis
TimePicker, TimeInput rememberTimePickerState() hour (0-23), minute, is24hour

This follows the pattern from state and remember: the state survives recomposition, and because the remember functions are built on rememberSaveable, the selection also survives rotation (see saveable and derived state).

A date picker in a dialog

Most apps show the calendar inside a dialog that the user confirms. Keep a boolean for "is the dialog open", and read the state only when the user presses OK.

Kotlin
// read-only example
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DueDateField(date: LocalDate?, onDateChange: (LocalDate) -> Unit) {
    var showPicker by rememberSaveable { mutableStateOf(false) }

    OutlinedButton(onClick = { showPicker = true }) {
        Text(date?.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)) ?: "Pick a date")
    }

    if (showPicker) {
        val pickerState = rememberDatePickerState(
            initialSelectedDateMillis = date?.toPickerMillis(),
        )
        DatePickerDialog(
            onDismissRequest = { showPicker = false },
            confirmButton = {
                TextButton(
                    enabled = pickerState.selectedDateMillis != null,
                    onClick = {
                        pickerState.selectedDateMillis?.let { onDateChange(it.toPickerDate()) }
                        showPicker = false
                    },
                ) { Text("OK") }
            },
            dismissButton = { TextButton(onClick = { showPicker = false }) { Text("Cancel") } },
        ) {
            DatePicker(state = pickerState)
        }
    }
}

Notice that the date lives in your screen state as a LocalDate, not as a Long. The picker's Long is an implementation detail that you convert at the boundary. The two helper functions toPickerMillis and toPickerDate are the subject of the next section.

DatePicker can also be placed directly in a layout, without a dialog, for example inside a bottom sheet. It has a showModeToggle option that lets the user switch between the calendar and a text input mode, and a title and headline slot for custom text.

The UTC milliseconds trap

selectedDateMillis is the number of milliseconds since 1970-01-01T00:00:00 UTC at the start of the selected day in UTC. It is not midnight in the user's time zone. A date is a calendar concept, and the picker stores it in the one zone every device agrees on.

That detail causes a very common bug. If you convert the milliseconds with the device's own zone, a user in New York who picks 15 March gets midnight UTC, which is 8 pm on 14 March in New York, and your code shows the 14th. Users east of Greenwich are safe by luck, which is why the bug often escapes testing.

The fix is to convert with ZoneOffset.UTC in both directions:

Kotlin
// read-only example: the two helpers used above
fun Long.toPickerDate(): LocalDate =
    Instant.ofEpochMilli(this).atZone(ZoneOffset.UTC).toLocalDate()

fun LocalDate.toPickerMillis(): Long =
    atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()

The first stand-in compares the two conversions for people in four zones. It is plain java.time, which behaves the same on Android (API 26 and up, or with core library desugaring on older versions, see Gradle build).

Kotlin The one-day-off bug (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Two related rules follow from this. First, when you need a moment in time (a reminder at a date and a clock time), do not store the picker millis. Combine a LocalDate and a LocalTime, attach the user's zone, and only then make an Instant. Second, to restrict choices you pass a SelectableDates object to rememberDatePickerState, and its functions also receive UTC millis, so use the same conversion inside it.

Kotlin
// read-only example: no past dates, no Sundays
@OptIn(ExperimentalMaterial3Api::class)
val futureWeekdays = object : SelectableDates {
    override fun isSelectableDate(utcTimeMillis: Long): Boolean {
        val date = utcTimeMillis.toPickerDate()
        return !date.isBefore(LocalDate.now()) && date.dayOfWeek != DayOfWeek.SUNDAY
    }
    override fun isSelectableYear(year: Int): Boolean = year >= LocalDate.now().year
}

Time pickers

A TimePicker is a clock dial; a TimeInput is the keyboard variant with two number fields. Both use the same TimePickerState. Unlike the date picker, there is no built-in dialog in Material 3 for the time picker, so you wrap it in an AlertDialog or build a small dialog of your own.

Kotlin
// read-only example
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TimePickerDialog(
    initial: LocalTime,
    onConfirm: (LocalTime) -> Unit,
    onDismiss: () -> Unit,
) {
    val state = rememberTimePickerState(
        initialHour = initial.hour,
        initialMinute = initial.minute,
        is24Hour = DateFormat.is24HourFormat(LocalContext.current),
    )
    AlertDialog(
        onDismissRequest = onDismiss,
        confirmButton = {
            TextButton(onClick = { onConfirm(LocalTime.of(state.hour, state.minute)) }) { Text("OK") }
        },
        dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
        text = { TimePicker(state = state) },
    )
}

Two points matter here:

  • state.hour is always 0 to 23, even when the picker shows the 12-hour clock with AM/PM. You never convert from AM/PM yourself.
  • Set is24Hour from the device setting (as above) so the picker matches the user's habit and the rest of the system.

A TimePicker is large, so on small screens or in landscape use TimeInput, which fits in a dialog without scrolling. You can switch between them with a toggle icon, just like the date picker's mode toggle.

The second stand-in models the time-picker state: 12-hour display derived from the 0-23 hour, and a validation rule on top (a reminder time must be inside opening hours).

Kotlin Time picker model: 24-hour state, 12-hour display (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Date ranges

When the user must choose a start and an end, such as a hotel stay or a report period, use DateRangePicker with rememberDateRangePickerState. Both ends are nullable: the user may have picked only the start so far. The same UTC rule applies to both values.

Kotlin
// read-only example
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StayPicker(onDone: (LocalDate, LocalDate) -> Unit) {
    val state = rememberDateRangePickerState()
    val start = state.selectedStartDateMillis
    val end = state.selectedEndDateMillis

    Column {
        DateRangePicker(
            state = state,
            modifier = Modifier.weight(1f),
            title = { Text("Select your stay", Modifier.padding(16.dp)) },
        )
        Button(
            enabled = start != null && end != null,
            onClick = { onDone(start!!.toPickerDate(), end!!.toPickerDate()) },
            modifier = Modifier.fillMaxWidth().padding(16.dp),
        ) { Text("Search") }
    }
}

Count the nights with ChronoUnit.DAYS.between(startDate, endDate), which is correct because both are plain dates (no daylight-saving surprises).

Putting it in your architecture

Treat the pickers as input devices, not as owners of data. The screen's UiState (see UI state and events) holds LocalDate? and LocalTime?; the picker is shown only while a flag is true; the confirm button calls a ViewModel function with already-converted values. That keeps the ViewModel free of Compose and Long quirks, and it makes the logic testable with ordinary unit tests, as shown in testing ViewModels.

Format dates for display with DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM). It follows the user's locale, so you never hard-code "dd/MM/yyyy". See accessibility and localization.

The pickers also exist in the older View system (MaterialDatePicker, MaterialTimePicker from Material Components), which return the same UTC-based millis for dates. Use them only inside Fragment-based screens.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does DatePickerState.selectedDateMillis represent?

    The picker stores a calendar date as midnight UTC. Converting with the device zone can shift the date by one day for users west of Greenwich.
  2. 2. A user in New York picks 15 March. Your code converts selectedDateMillis with ZoneId.systemDefault(). What do you get?

    Midnight UTC on the 15th is 8 pm (or 7 pm) on the 14th in New York, so the converted date is the 14th. Use ZoneOffset.UTC for the conversion.
  3. 3. TimePickerState shows 3:10 PM. What are state.hour and state.minute?

    hour is always on the 24-hour scale (0 to 23), even when the dial shows AM and PM.
  4. 4. Where should the picked date live in a well-structured screen?

    The picker is an input device. Convert at the boundary and keep a typed LocalDate in your state so it is testable and survives configuration changes.

Summary

  • Material 3 offers DatePicker, DatePickerDialog, DateRangePicker, TimePicker and TimeInput; each is driven by a remember...State object.
  • Date pickers return UTC-midnight milliseconds. Convert with ZoneOffset.UTC both ways to avoid the one-day-off bug.
  • TimePickerState.hour is always 0-23. Set is24Hour from the device setting.
  • There is no ready-made time picker dialog: wrap TimePicker in an AlertDialog.
  • Restrict choices with SelectableDates, which also receives UTC millis.
  • Keep LocalDate and LocalTime in your UI state; combine them with a zone to get an Instant.

Next: Tabs and Pagers