UIDatePicker setting minimum and maximum hour

醉酒当歌 提交于 2019-12-01 14:28:23

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];

    }
Srini Vasan
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.

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 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!