Search code examples
logicpseudocode

find difference between two selected hours


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.


Solution

  • 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