objective-cnsdate

Why does generating an NSDate from day, month, and year result in a completely wrong date?


I'm trying to generate an 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, and year = 2011:

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

Anyone know what might be going on?


Solution

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

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