Returning Time Components with Modulus

此生再无相见时 提交于 2020-01-13 05:46:23

问题


Someone does 20 Hours 42 Minutes & 16 Seconds in one shift totaling 74536 seconds. How do I get the hours from number of seconds the person has done for that shift?

20 * 60 * 60      =    72000
     42 * 60      =     2520
          16      =       16
                  +    -----
Total             =    74536
____________________________
Total % 60        =  Seconds (16)
Total % ?         =  Minutes (42)
Total % ?         =    Hours (20)

Tried 84600 already; turns out when a number is lower the modulus, it really is not very helpful, and something I am going to have to catch should someone only sign in for a few seconds ...


回答1:


You need to use both modulus and division:

t = seconds_in_shift;
secs = t % 60;
t /= 60;
mins = t % 60;
t /= 60;
hour = t;

Or:

secs =  ttime % 60;
mins = (ttime / 60) % 60;
hour =  ttime / 3600;

One other option uses the div() function from Standard C (<stdlib.h>):

div_t v1 = div(ttime, 60);
div_t v2 = div(v1.quot, 60);

After that, v1.rem contains the seconds; v2.rem contains the minutes, and v2.quot contains the hours based on the number of seconds originally in ttime.




回答2:


Based on Jonathan's reply, I believe the accurate answer should be this…

$total_time = 61000;
$sec = $total_time % 60;
$total_time = ($total_time - $sec) / 60;
$min = $total_time % 60;
$hour = ($total_time - $min) / 60;
echo "$hour hours, $min minutes and $sec seconds";

But if your server has PHP7 installed, you can use the intdiv() function. An integer division in which the remainder is discarded.

// $hour = ($total_time - $min) / 60; old code but still works
$hour = intdiv($total_time, 60); // PHP7 and above code


来源:https://stackoverflow.com/questions/2369137/returning-time-components-with-modulus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!