# SwiftUI forms: DatePicker

> Learn how to use the DatePicker control in SwiftUI to let users pick a date and time, and how displayedComponents limits it to just the date or time.

Author: Flavio Copes | Published: 2021-09-30 | Canonical: https://flaviocopes.com/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`:

```swift
@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:

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

Here's how it looks:

![iOS simulator showing SwiftUI DatePicker form with date and time fields displaying Sep 23, 2021 8:21 PM](https://flaviocopes.com/images/swiftui-forms-datepicker/Screen_Shot_2021-09-23_at_20.21.21.png)

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

![Date picker showing calendar view for September 2021 with day 23 highlighted in blue](https://flaviocopes.com/images/swiftui-forms-datepicker/Screen_Shot_2021-09-23_at_20.21.33.png)

![Time picker showing hour and minute selection wheels with 8:21 PM selected](https://flaviocopes.com/images/swiftui-forms-datepicker/Screen_Shot_2021-09-23_at_20.21.35.png)

Here's the full code of this example:

```swift
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:

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

![DatePicker with displayedComponents set to date only, showing Sep 23, 2021 without time](https://flaviocopes.com/images/swiftui-forms-datepicker/Screen_Shot_2021-09-23_at_20.23.05.png)

or just the time:

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

![DatePicker with displayedComponents set to hourAndMinute only, showing 8:23 PM without date](https://flaviocopes.com/images/swiftui-forms-datepicker/Screen_Shot_2021-09-23_at_20.23.21.png)
