SwiftUI: How to set a time picker's range to contain midnight?

Viewed 967

I am working with SwiftUI 2 and using a DatePicker with displayedComponents: .hourAndMinute.

I want to allow the user to choose any time between 10 pm and 2 am. Hence, the time range that I want to use contains midnight.

Unfortunately, when I supply the DatePicker with this time range, it only allows me to choose times between 10:00 pm and 11:59 pm:

@State private var date = Calendar.current.date(bySettingHour: 22, minute: 0, second: 0, of: Date())!
let startDate = Calendar.current.date(bySettingHour: 22, minute: 0, second: 0, of: Date())!

...

DatePicker("", selection: $date, in: startDate...Calendar.current.date(byAdding: .hour, value: 4, to: startDate)!, displayedComponents: .hourAndMinute)

In other words, only times until midnight can be chosen, although the supplied time range also contains 0 am until 2 am (of the next day).

How can this be solved?

1 Answers

By removing displayedComponents, everything seems to work as intended.

If your goal is to select any time between 10 pm and 2 am, this means 10PM today up to 2AM tomorrow, then displaying just hourAndMinute might be confusing

DatePicker("", selection: $date, in: startDate...Calendar.current.date(byAdding: .hour, value: 4, to: startDate)!)

Removing displayedComponents

Related