Stuck For A Day Trying To Get Modulo Operator Right

50 Views Asked by At

I'm writing a program to convert UTC (eg 2359) to a timezone (egg UTC+930)

For most cases it works using my formula (utc + utc-offset % 2400)

So for 7am + 9 hours: (700 + 900) % 2400 which evaluates to 1600 (4PM) and is correct

This does not work if it is something like 23:59 + 9 hours 45 minutes:

(2359 + 945) % 2400 = 904...which is wrong.

2

There are 2 best solutions below

1
On

There are $60$ minutes in an hour, not $100$, so you can't treat the time 23:59 as being the same as the number $2359$.

Add the minutes together first, then carry over an hour if necessary.

For example, $59$ minutes $+$ $45$ minutes $=$ $104$ minutes $=$ $1$ hour and $44$ minutes.

So 23:59 $+$ 9:45 = $23 + 9 + 1$ hours and $44$ minutes.

Modulo $24$ hours, this is $9$ hours and $44$ minutes.

0
On

The problem is you're looking in the wrong place for the error; your approach doesn't work for something like 07:59 + 1 minute either.

Usually, if you want to represent time as an integer that you can do arithmetic operations on, you store something like "minutes past midnight" so that you have a quantity on which ordinary arithmetic makes sense.

Keep in mind, however, that timekeeping is a complicated subject. Have you thought about how to deal with the switch between standard time and daylight savings time? Did you know some minutes have 61 seconds in them?

Most programming languages have built in functionality for working with time; for nearly every purpose you really should be using that functionality rather than trying to create your own. The people who write the libraries included with your programming language already know what the issues are, and the standard practices for dealing with those issues.