开发者

NSDate - Changing the year value

开发者 https://www.devze.com 2023-02-15 08:16 出处:网络
I need to change 开发者_开发知识库a NSDate object. What I am basically doing is changing the year value.

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.


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;


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


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消