Objective-C: Calculating Days, Minutes, Hours from seconds
Jan.20, 2009 in
Development, How To, Tech, mac osx
If you need to convert a total number of seconds into specific components (days, hours, minutes and seconds) in Objective-C, you can use this code snippet. You can probably do this a million other ways, but this works beautifully for me:
NSNumber *valueForDisplay = [NSNumber numberWithDouble:
[self valueForDisplay:clockName]];
NSNumber *totalDays = [NSNumber numberWithDouble:
([valueForDisplay doubleValue] / 86400)];
NSNumber *totalHours = [NSNumber numberWithDouble:
(([valueForDisplay doubleValue] / 3600) -
([totalDays intValue] * 24))];
NSNumber *totalMinutes = [NSNumber numberWithDouble:
(([valueForDisplay doubleValue] / 60) -
([totalDays intValue] * 24 * 60) -
([totalHours intValue] * 60))];
NSNumber *totalSeconds = [NSNumber numberWithInt:
([valueForDisplay intValue] % 60)];
The above assumes that valueForDisplay contains the total value in seconds. Enjoy.
Tags: maths, objective-c

February 10th, 2009 at 8:35 pm
Objective-C: Calculating Days, Minutes, Hours from seconds…
You’ve been kicked (a good thing) – Trackback from iPhoneKicks.com – iPhone SDK links, community driven…
February 10th, 2009 at 8:36 pm
Hey I have bookmarked this post on http://www.iphonekicks.com/objectivec/Objective_C_Calculating_Days_Minutes_Hours_from_seconds
February 13th, 2009 at 10:00 pm
Nice info – I have also kicked this on http://iPhoneKicks.com. Later today I will link to this for my blog readers.
August 12th, 2009 at 11:28 am
[...] Objective-C: Calculating Days, Minutes, Hours from seconds – Tech Thought. [...]
June 12th, 2010 at 2:39 pm
How would I get “number of months”?