开发者

Calculating time difference in 24-hour

I need to subtract two 24-hour time values from 0 to 23.

For example, 21:00 - 22:00 should return 23 hours and not -1 (!) hours.

I don't care about minutes.

I tried searching but couldn't get one. But I feel there's already a function for it, so didn't bother to write one.

Thank you,开发者_如何学Go all.


Subtract the two times and, if the result is negative, add 24.


Use modulo : (24+a-b)%24

(I assume that 11 is a typo here, and the correct answer is 23)


I think what you want is 21:00 - 22:00 gives 23 hours. In other words, if it is 10 o' clock today, then 9 o' clock tomorrow is 23 hours away. That's easy.

hours = (time1 - time2 + 24) % 24;

Where

  • time1 and time2 must be given in hours
  • % is the modulo operator

Why add 24? Adding the 24 inside the brackets gets around the problem of undefined behaviour when taking the modulo of negative numbers. This is better than an if statement because it doesn't stall the pipeline.


Just treat them as integers and normalize them to 0-23.

var c = (a%24 - b%24);
return c < 0 ? c+24;

If you really think 21:00 - 22:00 == 11, you must mean you want the difference in 12-hour hour values between the two times, which are expressed in 24-hour time, so you really want modulus 12:

var c = (a%12 - b%12);
return c < 0 ? c+12;

returns (9 - 10) + 12 = 11

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜