Search code examples
cocoacocoa-touchtime

Are time constants from Google's conversion function correct or is there a better built-in source in Cocoa?


I'm working with time interval calculations on iPhone and looking at some component values.

#define kSecondsInYear 31556926
#define kSecondsInMonth 2629744
#define kSecondsInDay 86400
#define kSecondsInHour 3600
#define kSecondsInMinute 60

I got these from Google's conversion function. I rounded Seconds in Month to nearest int.

Is this set of time constants correct or is there a better built-in source in Cocoa?


Solution

  • The way to handle time interval calculations in Cocoa is with NSDateComponents. The docs cover this well in Calendrical Calculations. Doing it this way handles most of the daylight savings time issues that can plague date calculations and should obviate the need to have constants for all these different units. If you still need them, the best way to get them is to ask NSCalendar. For example:

    NSRange r = [[NSCalendar currentCalendar] rangeOfUnit:NSSecondCalendarUnit 
                                              inUnit:NSYearCalendarUnit 
                                              forDate:[NSDate date]];
    NSUInteger secondsInThisYear = r.length; // Does not include leap seconds