UIDatePicker设置最小和最大小时

时间:2012-12-04 09:42:53

标签: objective-c ios uidatepicker

如何设置UIDatePicker的最小和最大小时数?一点都有可能吗?

我知道如何设置最短和最长日期:

[datePicker setMinimumDate:today]; [datePicker setMaximumDate:nextMonthDay];

我想要实现的是,选择器用户可以选择每天上午8点到晚上10点。

感谢。

4 个答案:

答案 0 :(得分:1)

希望以下代码可以帮助您。

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

    }

答案 1 :(得分:1)

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.

答案 2 :(得分:0)

您必须确保最短日期的时间是早上8点。最长日期晚上10点。 NSDateFormatter将帮助您根据需要创建日期对象。

答案 3 :(得分:0)

这适用于&#34; TIME MODE&#34;,否则选择的答案应该不直观地工作

    // 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)!

使用值并使用如下

    datePicker.datePickerMode = .time
    datePicker.date = selectedTime 
    datePicker.minimumDate = minTime 
    datePicker.maximumDate = maxTime