将秒转换为小时,分钟和秒

时间:2023-01-27 21:31:32

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:

我正在制作一个秒表应用程序。我正在计算应用程序在后台运行的时间,以便在应用程序返回前台时将其添加到秒表时间。我有这个代码,当NSNotification发送到我的StopwatchViewController时,调用的代码是以秒为单位的经过时间。我试图将秒转换为小时,分钟和秒:

-(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?

通知对象被分配给elapsedTime,但就是这样; elapsedHours / minutes / seconds都保持为0,并且elapsedTime保持不变。为什么不工作?

2 个解决方案

#1


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?

为什么不记录开始时间(如NSTimeInterval或NSDate)并从当前时间减去该值以获得经过的秒数?

#2


1  

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

你正在从elapsedTime中减去错误的部分。你应该减去小时而不是余数:

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

or you could use the equivalent calculation:

或者您可以使用等效计算:

elapsedTime = elapsedTime % 3600;

#1


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?

为什么不记录开始时间(如NSTimeInterval或NSDate)并从当前时间减去该值以获得经过的秒数?

#2


1  

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

你正在从elapsedTime中减去错误的部分。你应该减去小时而不是余数:

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

or you could use the equivalent calculation:

或者您可以使用等效计算:

elapsedTime = elapsedTime % 3600;