Generate NSDate from day, month, and year [closed]

我只是一个虾纸丫 提交于 2019-12-20 11:01:16

问题


I'm trying to generate a NSDate from a month day and year (all in integer format).

Right now my attempt is such:

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

However, _date outputs the following when day = 24, month = 8, year = 2011:

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

I must be doing something horribly wrong, but I have no idea what. Anyone know what might be going on?


回答1:


You have a typo in your code: (last line should be setYear:)

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



回答2:


One glaring glitch is:

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



回答3:


You are calling setMonth twice, the second time with the value for year. Should be:

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


来源:https://stackoverflow.com/questions/7664786/generate-nsdate-from-day-month-and-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!