Search code examples
iosswiftuidatepicker

Swift enable and disable time picker past time based on user input date


In my scenario, I am validating user input current date or different date based on it I need to enable and disable in time picker past time restriction. If user input current date then need to restrict past time in time picker otherwise need to show all time list.

My Code Below

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

Solution

  • You could do the following:

    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
    }