43
votes

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?

4
Came here at the end of 2016 and this question is still helpful. Given that there are 30 helpful votes on this, I would vote to re-open if possible. Additionally, none of the close voters have objective-c, iOS, cocoa-touch, cocoa, nsdate in their top tags looking at their profiles.C. Tewalt

4 Answers

42
votes

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

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

One glaring glitch is:

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

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

Apart from the typo nowadays (2019) there is a more convenient syntax to access dictionary values with key subscription and properties with dot notation

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

and there is another API without date components

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