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

Leave a Reply