views:

151

answers:

2

I need to display a date and, if it's not representing midnight, the time of that date using an NSDateFormatter. This is how I'm currently checking to see if it's midnight:

int minute = [[CalendarUtil cal]ordinalityOfUnit:NSMinuteCalendarUnit
                                          inUnit:NSDayCalendarUnit forDate:date];
if (minute == 1) {
    //time is midnight
}

[CalendarUtil cal] returns a static object, and no dates have time more specific than minutes (that is, it will always be on the minute, +- 0 seconds).

Is there any more practical or faster method to determine this?

A: 

NSDate is toll-free bridged to CFDateRef, and you can use that to get more useable information about the date. You could do something like this:

NSDate *date;
CFDateRef dr = date;
CFAbsoluteTime at = CFDateGetAbsoluteTime(dr);
CFTimeZoneRef tr = [NSTimeZone localTimeZone];
CFGregorianDate gd = CFAbsoluteTimeGetGregorianDate(at, tr);
if ((gd.hour == 0) && (gd.minute == 0) && gd.second == 0)) {
  ...
}

Whether that's faster or more practical, I don't know.

chrisbtoo
+1  A: 

chrisbtoo's answer is good. Here's another method for the sake of completeness:

NSCalendar* calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate* now = [NSDate date];
NSDateComponents* components = [calendar components:unitFlags fromDate:now];
if (([components hour] == 0) && ([components minute] == 0) && ([components second] == 0))
{
    ...
}
Shaggy Frog