Converting seconds into hours, minutes, and seconds

792 views Asked by At

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?

3

There are 3 answers

0
aepryus On

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;
1
Nikolai Ruhe On

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?

1
Michael Krebs On

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}')