Skip to content

SwiftUI forms: DatePicker

The DatePicker form control in SwiftUI lets us create a .. date picker.

How does it work?

First we create a property of type Date:

@State private var dateChosen = Date()

We use @State so that we can modify this value from our DatePicker view

Then we link that property to the DatePicker view:

DatePicker(selection: $dateChosen, in: ...Date()) {
    Text("Pick a date and time")
}

Here’s how it looks:

Tapping on each different part (date or time) will show a dedicate picker UI element:

Here’s the full code of this example:

struct ContentView: View {
    @State private var dateChosen = Date()

    var body: some View {
        Form {
            DatePicker(selection: $dateChosen, in: ...Date()) {
                Text("Pick a date and time")
            }
        }
    }
}

You can choose to only show one particular element of the date with the displayedComponents property, like just the date:

DatePicker(selection: $dateChosen, in: ...Date(), displayedComponents: .date) {
    Text("Pick a date and time")
}

or just the time:

DatePicker(selection: $dateChosen, in: ...Date(), displayedComponents: .hourAndMinute) {
    Text("Pick a date and time")
}


→ Get my Swift Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about swift: