Ask Your Question
2

What is the most efficient way to update SwiftUI DatePicker to allow only the current time and disallow future times?

asked 2022-10-09 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-02-16 19:00:00 +0000

devzero gravatar image

You can use the .maximumDate() modifier of the DatePicker to set the maximum selectable date to the current date and time. This will prevent the user from selecting a date or time in the future.

Here's an example:

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

    var body: some View {
        VStack {
            Text("Select a date and time:")
            DatePicker(
                "",
                selection: $selectedDate,
                displayedComponents: [.date, .hourAndMinute]
            )
            .labelsHidden()
            .maximumDate(Date())
        }
    }
}

In the example above, we're using the .maximumDate(Date()) modifier to set the maximum selectable date to the current date and time. You can customize the format of the displayed date and time components using the displayedComponents parameter.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-09 11:00:00 +0000

Seen: 8 times

Last updated: Feb 16 '23