Debugging dates and times
It’s a new year, and a good reminder of all the complexity of date and time calculations.
Last month, Debug December had a challenge to determine whether a year is a leap year or not. I had to look up the logic, and it was more complicated than I expected. I also find timezone conversions and calculations around dates unintuitive. Maybe it’s because of several dimensions of non-base-10 math. Or variable month lengths, leap years, daylight savings, etc.
Debugging when this goes wrong is usually one of the following:
- Different parts of infrastructure have different system clocks. (make sure clocks are synced or use a time-independent implementation)
- Unnecessary and/or erroneous conversion between time zones. (store in UTC and convert for clients)
- Implementing a transformation manually instead of using system/language/framework functionality. (use the libraries, please)
Thankfully, dates and times are all numbers and are deterministic, so test cases are straightforward to write for them.
P.S. System date and time is global state. Consider implementing a layer so that you can inject different system times easily for testing and potentially other features.