Search code examples
swiftuidatepicker

DatePicker disable sunday + opening times


I'm using this code:

    // 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)
    }

I want to block the sunday + hours before 8am and after 8pm. If someone selects a time that's out of our opening times it should scroll to a valid time. This code does not work properly because it'll scroll back to January 1st?

I've tried many variations on this without result.


Solution

  • I think it's best to determine if the closed hour is before or after midnight and then calculate a new date differently based on that

    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)
        }
    }