Hi,
I found a behavioural difference in the DatePicker between WatchOS and iOS when limiting the date and time range. In the code below I'm attempting to limit the date and time range so that dates and times in past can be chosen. In iOS the DatePicker hides the dates and times that are out of range but WatchOS only the DatePicker for the date does this. The time DatePicker allows all times. The output from DatePicker is limited to the valid range, so it appears that it's the DatePicker UI that doesn't match the iOS behaviour. Does anyone know if there's a way to DatePicker that chooses the time only show valid times like iOS?
import SwiftUI
struct HistoryPeriodView: View { @State private var selectedDate = Date() @State private var selectedTime = Date()
var body: some View {
VStack {
// Date Picker for selecting the date (Restricts to today or earlier)
DatePicker("Select Date", selection: $selectedDate, in: ...Date.now, displayedComponents: [.date])
.labelsHidden()
// Date Picker for selecting the time (Restricts to today or earlier)
DatePicker("Select Time", selection: $selectedTime, in: ...Date.now, displayedComponents: [.hourAndMinute])
.labelsHidden()
// Display selected Date & Time
Text("\(formattedDateTime)")
.font(.footnote)
.padding()
}
}
/// Formats the selected date and time for display
private var formattedDateTime: String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter.string(from: selectedTime)
}
}
#Preview { HistoryPeriodView() }