Reputation: 342
I'm trying to get the Total minutes for a Timer. I already got the seconds working. Here is how I got "Total Seconds":
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:time];
NSInteger hour = [comps hour];
NSInteger minute = [comps minute];
NSLog(@"Hour:%i", hour);
NSLog(@"minute:%i", minute);
NSInteger secs =hour * 60 * 60 + minute * 60;
NSNumber *elapsedSeconds = [[NSNumber alloc] initWithInt:secs];
NSDictionary *myDict = [NSDictionary dictionaryWithObject:elapsedSeconds forKey:@"TotalSeconds"];
Upvotes: 1
Views: 247
Reputation: 96353
That gives you wall-clock time, not a number of (whatever unit of time) that have elapsed.
To compute elapsed time, get the time as an NSTimeInterval (number of seconds) when you start, and then again every time you update the time-elapsed display (including when you finish). Subtract the earlier time from the later time, and the result will be the number of seconds elapsed.
You can break this down into days, hours, minutes, and seconds by repeated divisions and their remainders. For the latter, use the fmod
or remainder
function (the %
operator does not work on floating-point values). Divide total seconds by 60.0 to get minutes; the remainder will be the number of seconds after the minutes (e.g., 613 / 60
= 10 minutes; fmod(613, 60)
= 13 seconds). Do the same to the total minutes to get hours and minutes. For days, of course, do it to the hours with 24 as the divisor.
Upvotes: 1