Search code examples
objective-ciosnsdate

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

Solution

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