user2397282
user2397282

Reputation: 3818

Converting seconds into hours, minutes, and seconds

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?

Upvotes: 0

Views: 780

Answers (3)

Michael Krebs
Michael Krebs

Reputation: 11

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

Upvotes: 0

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81878

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?

Upvotes: 2

aepryus
aepryus

Reputation: 4825

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;

Upvotes: 1

Related Questions