Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateComponents returning nil

I'm trying to get an NSDate object with the hour, minute, and second initialized to 0. I'm using the code below to get it, but for some reason I get nil from [NSDateComponents date]. What's wrong with my code?

NSCalendar *gregorian = [[[NSCalendar alloc]
                          initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDate *now = [[[NSDate alloc] init] autorelease];
NSDateComponents *nowDc = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) 
        fromDate:now];
// this returns nil!
NSDate *todayStart = [nowDc date];
like image 535
Ovesh Avatar asked Feb 27 '11 11:02

Ovesh


1 Answers

When you get the components from a calendar instance the calendar of the NSDateComponents instance is not set.

But you have to set the calendar before you can use [components date], because without calendar there is no date.

So try to add [nowDc setCalendar:gregorian];

like image 89
Matthias Bauch Avatar answered Nov 02 '22 20:11

Matthias Bauch