在 Objective C 中,NSDateComponents *comps = [[NSDateComponents alloc] init];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];
NSInteger year = components.year;
NSInteger month = components.month;
NSInteger day = components.day;
NSInteger minimumYear = year - 1900;//Given some year here for example
NSInteger minimumMonth = month - 1;
NSInteger minimumDay = day - 1;
[comps setYear:-minimumYear];
[comps setMonth:-minimumMonth];
[comps setDay:-minimumDay];
NSDate *minDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[datePicker setMinimumDate:minDate];
[datePicker setMaximumDate:[NSDate date]];
最短日期是 1900 年 1 月 1 日。我希望它对你们所有人都有效.. :)
在 Swift 2.0 或更高版本中
let calendar = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian);
let todayDate = NSDate()
let components = calendar?.components([NSCalendarUnit.Year,NSCalendarUnit.Month,NSCalendarUnit.Day], fromDate: todayDate)
let minimumYear = (components?.year)! - 1900
let minimumMonth = (components?.month)! - 1
let minimumDay = (components?.day)! - 1
let comps = NSDateComponents();
comps.year = -minimumYear
comps.month = -minimumMonth
comps.day = -minimumDay
let minDate = calendar?.dateByAddingComponents(comps, toDate: todayDate, options: NSCalendarOptions.init(rawValue: 0))
datePicker.minimumDate = minDate
datePicker.maximumDate = datePicker.date