0

I am making a stopwatch app. I am counting the time elapsed since the app was in the background, so that I can add it on to the stopwatch time when the app returns to the foreground. I have this code which is called when an NSNotification is sent to my StopwatchViewController with the elapsed time in seconds. I am trying to convert the seconds into hours, minutes and seconds:

-(void)newMessageReceived:(NSNotification *) notification
{

    elapsedTime = [[notification object] intValue];

    elapsedHours = elapsedTime / 3600;
    elapsedTime = elapsedTime - (elapsedTime % 3600);

    elapsedMinutes = elapsedTime / 60;
    elapsedTime =  elapsedTime - (elapsedTime % 60);

    elapsedSeconds = elapsedTime;

    secondInt = secondInt + elapsedSeconds;
    if (secondInt > 59) {
        ++minuteInt;
        secondInt -= 60;
    }

    minuteInt = minuteInt + elapsedMinutes;
    if (minuteInt > 59) {
        ++hourInt;
        minuteInt -= 60;
    }

    hourInt = hourInt + elapsedHours;
    if (hourInt > 23) {
        hourInt = 0;
    }
} 

The notification object is assigned to elapsedTime, but that is it; elapsedHours/minutes/seconds all stay at 0, and elapsedTime stays the same. Why isn't it working?

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
user2397282
  • 3,798
  • 15
  • 48
  • 94
  • I'd just keep an `totalTime` value, increment it, and *then* convert to hours/minutes/seconds. As to your algorithm, you're messing up with the `elapsedTime = elapsedTime - (elapsedTime % 3600);` lines. Break that expression down to separate assignments so you can examine the intermediate results and you will find your problem. – Hot Licks Dec 07 '13 at 14:03

3 Answers3

2

This approach seems overly complicated and error prone.

Why not just record the start time (as NSTimeInterval or NSDate) and subtract that from the current time to get the elapsed seconds?

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
1

You are subtracting off the wrong part from elapsedTime. You should be subtracting the hours not the remainder:

elapsedTime = elapsedTime - (elapsedTime / 3600) * 3600;

or you could use the equivalent calculation:

elapsedTime = elapsedTime % 3600;
aepryus
  • 4,715
  • 5
  • 28
  • 41
0

Convert seconds in h m s with the usage of type conversion float to int

seconds = 111222333  # example 

h = (seconds/60/60) 
m = (h-int(h))*60
s = (m - int(m))*60

Check the result

print(f'{h:.0f} {m:.0f} {s:.0f}')
David Buck
  • 3,752
  • 35
  • 31
  • 35
  • it is necessary to import math and round down the h and mins:(f'the sequential runtime of table {table[0]} is {math.floor(h):.0f} hours {math.floor(m):.0f} min {s:.0f} s ') – Michael Krebs Sep 28 '20 at 23:50