简体   繁体   中英

UIDatePicker setting minimum and maximum hour

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]; [datePicker setMaximumDate: nextMonthDay];

What i want to achieve is that in picker user could select from 8 am to 10 pm every day.

Thanks.

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM