NSDate - year value change

I need to modify the NSDate object. What I basically do is change the value of the year.

eg:

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 the 'date' return 2011-03-06 22:17:50 +0000 from init, I would like to create a date from 2093-03-06 22:17:50 +0000.

However, I would like it to be as culturally neutral as possible, so it will work regardless of time zone.

Thank.

+3
source share
4 answers

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

+2
source

Here is my code for setting the UIDatePicker limits for choosing a date of birth. Maximum age - 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;
+8
source

, .

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];
+3

iOS 8 . :

date = [calendar dateBySettingUnit:NSCalendarUnitYear value:year ofDate:date options:0];
+2
source

Source: https://habr.com/ru/post/1796690/