admin管理员组

文章数量:1426950

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, all.

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, all.

Share Improve this question edited Jan 27, 2011 at 17:20 kapeels asked Jan 27, 2011 at 17:14 kapeelskapeels 1,7025 gold badges30 silver badges52 bronze badges 2
  • 1 Huh? How does 21:00-22:00=11 hours? – Michael Kopinsky Commented Jan 27, 2011 at 17:16
  • how do 21 and 22 get to be 11? I mean, I would understand 23, but 11? – Nanne Commented Jan 27, 2011 at 17:19
Add a ment  | 

4 Answers 4

Reset to default 3

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

本文标签: javascriptCalculating time difference in 24hourStack Overflow