views:

32

answers:

3

For 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.

A: 

Well that's the number of seconds in 1/12 of a year, not exactly one month since different months are different lengths. Would that cause a problem in your application?

sixfoottallrabbit
As long as the error is less that about 2 hours in the past 70 years, I'm good.
willc2
+1  A: 

There are 86400 seconds in a day, unless of course it's a leap second year in which case there's 86401 seconds in one of the days. 2008 was such a year.

There's 31556926 seconds in a year, unless it's a leap second year, in which case add one second. If it's a leap year, add a day's worth of seconds.

And as sixfoottallrabbit pointed out, the number of seconds in a month varies depending on if it's a 28,29,30 or 31 day month.

Given the above I think it's unlikely that Cocoa would define constants for the following, but I may be wrong as it's just a guess.

  • Seconds in a year
  • Seconds in a month
  • Seconds in a day
Glen
A: 

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
Rob Napier