3

I'm trying to set maximum and minimum hour in my Datepicker. I managed to set minimum, but cannot resolve maximum. Here is what I have so far:

    let startHour: Int = 8
    let endHour: Int = 22
    let date1: NSDate = NSDate()
    let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let components: NSDateComponents = gregorian.components(([.Day, .Month, .Year, .Hour, .Minute]), fromDate: date1)

    if components.hour >= 22 && components.hour < 8 {
        components.hour = startHour
        components.minute = 0
        components.second = 0
    }

    let startDate: NSDate = gregorian.dateFromComponents(components)!

    components.hour = endHour
    components.minute = 0

    let endDate: NSDate = gregorian.dateFromComponents(components)!

    picker.datePickerMode = .DateAndTime
    picker.minimumDate = startDate
    picker.maximumDate = endDate
    picker.setDate(startDate, animated: true)

Is there a way to ignore current day and month in method .maximumDate (which is now my current date)? It sets my picked future date back to current date and checking only hour interval which is set to 8am - 10pm. I want DatePicker to enable picking hours starting from 8am to 10pm for every future day, not only current day.

  • Possible duplicate of [Limiting UIDatePicker dates from a particular time. Such as Input DOB to a restricted age limit](http://stackoverflow.com/questions/31418218/limiting-uidatepicker-dates-from-a-particular-time-such-as-input-dob-to-a-restr) – Tarvo Mäesepp Jul 12 '16 at 13:52
  • That solution does not fit my example. It allows me to expand the range of dates, but then I can pick hours from 10pm to 8am, which is not what I wanted. – Adrian Krzyżowski Jul 12 '16 at 14:25

1 Answers1

3

Remove picker.maximumDate = endDate and write your own custom validation method.

// Call datePickerChanged method when the picker finishes rotating
picker.addTarget(self, action: #selector(datePickerChanged(_:)), forControlEvents: .ValueChanged)

func datePickerChanged(picker: UIDatePicker) {
    let selectedDate = picker.date
    // 1) if selectedDate's hour > than your endHour (10pm)
    // 2) create yourNewDate with endHour = 10pm
    // 3) set new date with animation
    picker.setDate(yourNewDate, animated: true)
}
Jon
  • 3,208
  • 1
  • 19
  • 30