NSException NSException - 4 years ago 132
iOS Question

Minimum and maximum date in UIDatePicker

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 date.

Suppose current year is 2018 then I want minimum date 2000 and maximum date 1918.

What I have done so far is :

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];

NSInteger year = [components year];

int mindt = year - 18;

int maxdt = year -100;

// NSDate * MinDate = [components year] - 18;

// NSDate * MaxDate = [components year] - 100;

// self.datePicker.minimumDate = MinDate;

// self.datePicker.maximumDate = MaxDate;


but I cant get this integer to my date format..

Answer Source

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:

let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!   
let currentDate: NSDate = NSDate() 
let components: NSDateComponents = NSDateComponents()

components.year = -18
let minDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

components.year = -150
let maxDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!

self.datePicker.minimumDate = minDate
self.datePicker.maximumDate = maxDate
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download