UIDatePicker setting minimum and maximum hour

前端 未结 4 624
孤独总比滥情好
孤独总比滥情好 2021-01-17 03:07

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

相关标签:
4条回答
  • 2021-01-17 03:21

    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 
    
    0 讨论(0)
  • 2021-01-17 03:29

    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];
    
        }
    
    0 讨论(0)
  • 2021-01-17 03:33
    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.
    
    0 讨论(0)
  • 2021-01-17 03:36

    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.

    0 讨论(0)
提交回复
热议问题