How to set minimum and maximum hour to UIDatePicker ? At all is it possible ?
I know how to set minimum and maximum date:
[datePicker setMinimumDate: today];
This works in "TIME MODE", otherwise selected answer should work unintuitively though
// minimum time
components.hour = 0
components.minute = 0
let minTime = calendar.date(from: components)
// max time
components.hour = 23
components.minute = 59
let maxTime = calendar.date(from: components)
// selected value current time or saved time
let selectedDate = Date() // or saved time
let nowComp = calendar.dateComponents([.hour, .minute], from: selectedDate)
components.hour = nowComp.hour
components.minute = nowComp.minute
let selectedTime = calendar.date(from: components)!
play with the values and use as below
datePicker.datePickerMode = .time
datePicker.date = selectedTime
datePicker.minimumDate = minTime
datePicker.maximumDate = maxTime
Hope the following code help you.
- (IBAction)dataPickerValueChanged:(UIDatePicker *)sender {
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:[testDatePicker date]];
if ([dateComponents hour] > 8 && [dateComponents hour] < 22) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error!" message:@"This time cant be selected" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
[alert show];
return;
}
lblDate.text = [sender date];
}
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSIntegerMax fromDate:self.datePicker.date];
[components setHour:hour];
[components setMinute:minutes];
[components setSeconds:seconds];
NSDate *date [[NSCalendar currentCalendar] dateFromComponents:components];
self.datePicker.minimumDate = date;
//same for maximumDate do this.
You have to make sure that time in your minimum date is 8 am & 10 pm in maximum date. NSDateFormatter will help you to create your date objects as you want.