我正在使用以下代码:
// Disallow sundays, after 8pm and before 8am
if weekday == 1 {
datePicker.setDate(Date(timeInterval: 60*60*24*1, since: datePicker.date), animated: true)
}
if hour >= 20 && minute > 0 {
let calendar = Calendar.current
var components = DateComponents()
components.hour = 9
components.minute = 00
datePicker.setDate(calendar.date(from: components)!, animated: false)
}
if hour < 8 {
let calendar = Calendar.current
var components = DateComponents()
components.hour = 9
components.minute = 00
datePicker.setDate(calendar.date(from: components)!, animated: false)
}
我想在星期日上午8点之前和晚上8点之后封锁几个星期天。 如果有人选择的时间不在我们的开放时间之内,则应滚动到有效时间。该代码无法正常运行,因为它将回滚至1月1日?
我对此进行了很多尝试,都没有结果。
答案 0 :(得分:1)
我认为最好确定封闭时间是在午夜之前还是之后,然后根据该时间以不同的方式计算新日期
let calendar = Calendar.current
if weekday == 1 || 20...23 ~= hour {
if let next = calendar.date(byAdding: .day, value: 1, to: date),
let opening = calendar.date(bySettingHour: 9, minute: 0, second: 0, of: next) {
datePicker.setDate(opening)
}
} else if 0..<8 ~= hour {
if let opening = calendar.date(bySettingHour: 9, minute: 0, second: 0, of: date) {
datePicker.setDate(opening)
}
}