在我的情况下,我正在验证用户输入的当前date
或基于它的其他日期,我需要在时间选择器中启用和禁用过去的时间限制。如果用户输入当前日期,则需要限制过去的时间picker
,否则需要显示所有time
列表。
下面的我的代码
// MARK: Validate Current Date or Not Based on it Need to enable and disable timepicker past time
let dateCurrents = Date()
let formatters = DateFormatter()
formatters.dateFormat = "yyyy-MM-dd"
let resultDate = formatters.string(from: dateCurrents)
if fullDate == resultDate {
print("Same Date Past Time Disabled")
let nows = Date()
timePickerView.minimumDate = nows
timePickerView.date = nows
} else {
print("Different Date Past Time Enabled")
timePickerView.minimumDate =
timePickerView.date = // Need to Enable Past Time
}
您可以执行以下操作:
let fullDate = datePickerView.date
let now = Date()
let calendar = Calendar.current
let result = calendar.compare(now, to: fullDate, toGranularity: .day)
let isSameDay = result == .orderedSame
if isSameDay {
print("Same Date Past Time Disabled")
timePickerView.minimumDate = now
timePickerView.date = now
} else {
print("Different Date Past Time Enabled")
timePickerView.minimumDate = nil
timePickerView.date = now
}