Minimum and maximum date in UIDatePicker

前端 未结 11 1285
不知归路
不知归路 2020-11-30 00:34

I want to get the minimum and maximum date from a date picker, but minimum date should be \"- 18\" of the current date and the maximum date should be \"- 100\" of current da

11条回答
  •  时光说笑
    2020-11-30 00:54

    Try this:

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *currentDate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:-18];
    NSDate *minDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
    [comps setYear:-150];
    NSDate *maxDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
    [comps release];
    
    self.datePicker.minimumDate = minDate;
    self.datePicker.maximumDate = maxDate;
    

    It may be easily translated to Swift 4.2:

        let calendar = Calendar(identifier: .gregorian)
    
        let currentDate = Date()
        var components = DateComponents()
        components.calendar = calendar
    
        components.year = -18
        components.month = 12
        let maxDate = calendar.date(byAdding: components, to: currentDate)!
    
        components.year = -150
        let minDate = calendar.date(byAdding: components, to: currentDate)!
    
        picker.minimumDate = minDate
        picker.maximumDate = maxDate
    

提交回复
热议问题