从日,月和年生成NSDate

时间:2011-10-05 16:47:03

标签: objective-c ios cocoa-touch cocoa nsdate

我正在尝试从一个月和一年生成一个NSDate(全部采用整数格式)。

现在我的尝试是这样的:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSNumber *day = [dataSource valueForKey:@"day"];
NSNumber *month = [dataSource valueForKey:@"month"];
NSNumber *year = [dataSource valueForKey:@"year"];
[components setDay:[day intValue]];
[components setMonth:[month intValue]];
[components setMonth:[year intValue]];
NSDate *_date = [calendar dateFromComponents:components];

但是, _date 在day = 24,month = 8,year = 2011时输出以下内容:

  

0168-07-25 04:56:02 +0000

我必须做一些可怕的错误,但我不知道是什么。任何人都知道可能会发生什么?

4 个答案:

答案 0 :(得分:40)

您的代码中有拼写错误:(最后一行应为setYear:

 [components setDay:[day intValue]];
 [components setMonth:[month intValue]];
 [components setYear:[year intValue]];

答案 1 :(得分:3)

一个明显的故障是:

[components setMonth:[year intValue]];    //setting month with year!

答案 2 :(得分:2)

您正在调用setMonth两次,第二次调用year的值。应该是:

[components setDay:[day intValue]];
[components setMonth:[month intValue]];
[components setYear:[year intValue]];

答案 3 :(得分:0)

除了如今的错字(2019),还有一种更方便的语法来访问带有键订阅的字典值和带有点标记的属性

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSNumber *day = dataSource[@"day"];
NSNumber *month = dataSource[@"month"];
NSNumber *year = dataSource[@"year"];
components.day = day.integerValue;
components.month = month.integerValue;
components.year = year.integerValue;
NSDate *_date = [calendar dateFromComponents:components];

还有另一个没有日期成分的API

NSCalendar *calendar = [NSCalendar currentCalendar];
NSNumber *day = dataSource[@"day"];
NSNumber *month = dataSource[@"month"];
NSNumber *year = dataSource[@"year"];
NSDate *_date = [calendar dateWithEra:1 year:year.integerValue month:month.integerValue day:day.integerValue hour:0 minute:0 second:0 nanosecond:0];