Disable Past date selection in DatePicker SwiftUI

In this tutorial, we will see how to disable the selection of past dates in a DatePicker in SwiftUI.

In SwiftUI, we can disable past dates in a DatePicker by setting a minimum date that the user can select. We can do this using the DatePicker with a Date binding and a Date range.

Disable past date from the current date

Now, in the below I will create a program that will disable all the past date from current date (today), and we can only select the future dates.

Example

import SwiftUI

struct ContentView: View {
    @State private var selectedDate = Date()
    
    var body: some View {
        DatePicker("Select a Date", selection: $selectedDate, in: Date()..., displayedComponents: .date)
            .labelsHidden()
    }
}

In the above program, I have bound the selectedDate property to the selected date in the DatePicker, so we can use this date in our SwiftUI view or for further processing.

Then, I have set the in parameter of the DatePicker to Date()..., which means that it will allow selecting dates starting from the current date (today) and onwards. This will effectively disable past dates in the date picker.

By using the Date()... range, we ensure that only dates in the future are selectable. This prevents users from selecting past dates in the date picker.

Output:

Disable Past date selection in DatePicker SwiftUI

Disable past date from a specific date

Similarly, in the below I will create a program that will disable all the past date from a specific date.

We can do that by passing the specific date, month and year into the from: DateComponents(...) method.

Example

import SwiftUI

struct ContentView: View {
    @State private var selectedDate = Date()
    let minimumSelectableDate = Calendar.current.date(from: DateComponents(year: 2023, month: 10, day: 7)) ?? Date()

    var body: some View {
        DatePicker(
            "Select a date",
            selection: $selectedDate,
            //Set the minimum selectable date and allow any future date
            in: minimumSelectableDate...,
            displayedComponents: .date
        )
            .labelsHidden()
    }
}

In the above program, I have declared a variable called minimumSelectableDate that will specifies the minimum selectable date for the DatePicker.

I have set the  minimum date to October 7, 2023, using the Calendar.current.date(from: DateComponents(...)) method. If the date cannot be created for any reason, it defaults to the current date using the ?? operator.

Output:

Disable Past date selection in DatePicker SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *