NSDate - 更改年份值

时间:2011-03-06 22:20:19

标签: objective-c ios4 nsdate

我需要更改NSDate对象。我基本上做的是改变年份值。

例如:

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

所以当'date'从init返回2011-03-06 22:17:50 +0000时,我想用2093-03-06 22:17:50 +0000创建一个日期。

但是我希望这在文化上尽可能中立,所以无论时区如何都可以。

感谢。

4 个答案:

答案 0 :(得分:8)

这是我为出生日期选择设置UIDatePicker限制的代码。允许的最大年龄是100岁

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

答案 1 :(得分:3)

查看NSCalendar,尤其是components:fromDate:dateFromComponents:方法。

答案 2 :(得分:3)

我设法用Hoha给我的指针来找出答案。

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 :(得分:3)

从iOS 8开始,您可以设置特定的日期组件。例如:

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