I have two selected hours that is taken from 0-23 range. How to programatically calculate difference between them? For example, diff between 22 and 4 would be 6, 22 and 24 - 2.
2 Answers
This is an example of a modulo 24 arithmetic (for more info on modular arithmetic ).
Times are congruent modulo 24, there's a congruence (or equivalence) with respect 24 (e.g., 1 is congruent (or equivalent) to 25). You could just calculate the module of the difference.
(second_time - first_time) modulo 24
In your example,
(4 - 22) modulo 24 = -18 modulo 24 = 6
(24 - 22) modulo 24 = 2 modulo 24 = 2
EDIT:
Just to go into a bit more detail. This answer is taking into account just the details you specified in your question, i.e. hours taken from 0-23. If you are trying to achieve something more complex there's a lot of corner cases and exceptions to take into account.
For example, with my method you wouldn't be able to get a difference between 0:00 and 24:00, because they are a equivalent time, so you would need a specific case for it. Any way, if the times are just taken from 0 to 23 as stated, the difference between 0:00 and 0:00 would depend on if they are the same time or 24h cycle later, this would happen with any two equal times (6:00 to 6:00, is it the same day or +N days?). So you would need to have a date additionally to solve this ambiguity.
More complications would arise if you're using minutes, if you're taking into account time zones, leap seconds, and all that.
Depending on the language you are using, you could have complications with the modulo operator over negative numbers, so you should think about that too (adding the cycle time would fix it). So doing instead:
(second_time - first_time + 24) modulo 24

- 36
- 4
-
what about 3 and 6 for example? – mk_yo May 13 '16 at 08:49
-
Same thing applies. The time between 3 and 6 would be: (6 - 3) modulo 24 = 3 modulo 24 = 3 And between and 6 and 3: (3 - 6) modulo 24 = -3 modulo 24 = 21 I've also edited my previous answer with some more detail because apparently someone thought it was a bad answer but didn't care to explain what was wrong. I hope this is better now and that I'm not being unaware of something terribly wrong in my answer. – Vayolet May 13 '16 at 12:15
Let us assume the first_time to the first selected hour and second_time to be the second selected hour.
Pseudo code:
if first_time > 12:
first_time = 24 - first_time
if second_time < 12:
second_time = -second_time
time_difference = abs(first_time - second_time)
If you need absolute difference you can use a abs() function else you can exclude that.

- 368
- 1
- 3
- 10
-
-
This logic fails for the case you mentioned, the modulo logic described by Vayolet is the right way to do it. – ajays20078 May 13 '16 at 13:49