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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With