Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 864
NSException Avatar asked May 08 '12 07:05

NSException


2 Answers

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 
like image 107
tilo Avatar answered Oct 11 '22 12:10

tilo


Look at this for Swift version. User negative value (-) to subtract and positive value to add date component.

1. Set minimum date

 yourDatePicker.minimumDate = Calendar.current.date(byAdding: .year, value: -1, to: Date()) 

2. Set maximum date

 yourDatePicker.maximumDate = Calendar.current.date(byAdding: .year, value: 1, to: Date()) 
like image 38
Rahul Panzade Avatar answered Oct 11 '22 10:10

Rahul Panzade