How to Select a Date with DatePicker in SwiftUI

SwiftUI-DatePicker-small.gif

If you need to give your users a way to pick a date and time (say, for creating a calendar entry) then read on to learn how to use a DatePicker to do just that.

What is a DatePicker?

The DatePicker view in SwiftUI displays a scrollable control with 4 “components” to select an absolute date. The components are:

  • Date (with day of week)

  • Hour for the time

  • Minutes for the time

  • AM/PM

Creating a DatePicker

Creating a DatePicker is just as easy as most controls in SwiftUI. Just give it a binding to a state property (for storing the selected date) and label and you’re all set!

@State private var selectedDate = Date()

var body: some View {
    VStack {
        Text("\(selectedDate)")
            .multilineTextAlignment(.center)
        DatePicker(selection: $selectedDate) {
            Text("Select a date")
        }
        .labelsHidden()
    }
}

Check out some other recent tutorials

Previous
Previous

Using dropLast and removeLast in Swift

Next
Next

How to Push a Detail View Using NavigationLink