3

I need to change a NSDate object. What I am basically doing is changing the year value.

for example:

NSString *someYear = @"2093";
    NSDate *date = [NSDate date]; // Gets the current date.
    ... Create a new date based upon 'date' but with specified year value.

So with 'date' returning 2011-03-06 22:17:50 +0000 from init, I would like to create a date with 2093-03-06 22:17:50 +0000.

However I would like this to be as culturally neutral as possible, so it will work whatever the timezone.

Thanks.

Mick Walker
  • 3,862
  • 6
  • 47
  • 72

4 Answers4

8

Here's my code for setting the UIDatePicker limits for a Date Of Birth selection. Max age allowed is 100yrs

    _dateOfBirth.maximumDate = [NSDate date];

    //To limit the datepicker year to current year -100
    NSDate *currentDate = [NSDate date];
    NSUInteger componentFlags = NSYearCalendarUnit;
    NSDateComponents *components = [[NSCalendar currentCalendar] components:componentFlags fromDate:currentDate];
    NSInteger year = [components year];
    NSLog(@"year = %d",year);
    [components setYear:-100];
    NSDate *minDate =  [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:currentDate  options:0];
    _dateOfBirth.minimumDate = minDate;
Joe M
  • 669
  • 6
  • 9
3

Starting in iOS 8 you can set an specific date component. For example:

date = [calendar dateBySettingUnit:NSCalendarUnitYear value:year ofDate:date options:0];
hpique
  • 119,096
  • 131
  • 338
  • 476
3

Take a look at NSCalendar, especially components:fromDate: and dateFromComponents: methods.

hoha
  • 4,418
  • 17
  • 15
3

I managed to figure the answer with the pointer Hoha gave me.

NSNumber *newYear = [[NSNumber alloc] initWithInt:[message intValue]];
    NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned int unitFlags = NSYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
    NSDateComponents* dateComponents = [gregorian components:unitFlags fromDate:[NSDate date]];
    [dateComponents setYear:[newYear intValue]];
    NSDate *newDate = [gregorian dateFromComponents:dateComponents];
    [newYear release];
Mick Walker
  • 3,862
  • 6
  • 47
  • 72
  • 1
    Actually you can get current calendar (one according to device settings) with `[NSCalendar currentCalendar]` or `[NSCalendar autoupdatingCurrentCalendar]`. – hoha Mar 06 '11 at 22:48