18

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];
Ovesh
  • 5,209
  • 11
  • 53
  • 73

1 Answers1

35

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

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
  • OK, where does it say that in the docs? What an annoying implementation. – Ovesh Feb 27 '11 at 13:11
  • 3
    It doesn't say that explicitly. But it is implied throughout the Date Programming guide. The distinction between NSDate (as point in time) and day month year is pretty important. Because of the same reason there is no [NSDate dateWithYear:month:date] method. Without a NSCalendar day month and year are meaningless. – Matthias Bauch Feb 27 '11 at 14:19
  • 1
    This is confusing because you're creating the Date Components from an NSCalendar method (`NSDateComponents *components = [[NSCalendar currentCalendar] components: ...`). I would have assumed that the specified Calendar would be automatically set on the Components. But no, you have to set the calendar "again" on the next line... – pkamb Feb 09 '16 at 17:24