Create a date picker using DatePicker in SwiftUI


SwiftUI has the built-in DatePicker control which allows Apple developers to create a date picker in a simple and easy way. All the complicated tasks are already done by SwiftUI behind the scene. You only have to write code to use the DatePicker control.

Just like many other controls that store values, DatePicker also needs to be bound with a state variable.

Let’s see our first simple example of creating a date picker using the SwiftUI DatePicker:

    @State private var dateOfBirth = Date.now
    
    var body: some View {
        
        DatePicker("Birth date", selection: $dateOfBirth)
   
    }

As you can see in the above example, we have a date and time picker for the chosen date. But sometimes time picker doesn’t make any sense. So, we can remove the time picker and keep only the date picker.

Removing the time picker

In order to remove the time from the date picker, you can set the displayedComponents to date. Below is how we can do it:

    @State private var dateOfBirth = Date.now
    
    var body: some View {
        
        DatePicker("Birth date", selection: $dateOfBirth, displayedComponents: .date)
            .padding()
   
    }
SwiftUI DatePicker

In this case, we don’t have the time in the date picker. This is because we have set the date component to the displayedComponents.

Set DatePicker label using Text view

You can use the label for SwiftUI DatePicker using Text view also instead of providing it directly inline. Here is an example:

    @State private var dateOfBirth = Date.now
    
    var body: some View {
        
        DatePicker(selection: $dateOfBirth, displayedComponents: .date) {
            Text("Birth date")
                .foregroundColor(.mint)
        }
        .padding()
   
    }
SwiftUI DatePicker with green label text

Showing up value from the date picker

As a state variable is bonded to our date picker, it is easier to show up the live value of the chosen date. Below we are using Text view to display the live date chosen:

    @State private var dateOfBirth = Date.now
    
    var body: some View {
        
        DatePicker(selection: $dateOfBirth, displayedComponents: .date) {
            Text("Birth date")
                .foregroundColor(.mint)
        }
        .padding()
        
        Text("Birth date is \(dateOfBirth.formatted(date: .long, time: .omitted))")
   
    }
Date picker value showing up using text view

Changing the date in the DatePicker will change the date showing up using text view.