A friend of mine recently asked me whether to store DateTime in UTC or with TimeZones within a database column and Why?
Thinking about it made me remember all the bugs I had to deal with over the years due to DayLight savings and TimeZone conversions.
I am writing this article to share some of my learnings on how to handle Time in software systems and links to a few blog posts I feel have done an amazing job explaining the complexities of dealing with DateTime.
I generally follow these guidelines when it comes to handling time:
Why
- Dealing with timezones is highly complex.
- Local country authorities govern local timezones.
- Having Time in multiple timezones make it harder to reason about business logic.
- UTC is the time standard against which all the world’s timekeeping is synchronised (or coordinated). It is not, itself, a time zone but rather a transcendent standard that defines what Time zones are.
What
- Use UTC as my server’s time zone
- Use UTC as the timezone to store all DateTime in my database
- Deal with time zone presentation in my application’s layer
- Deal with time zone schedule jobs in my application’s layer
How
- Use libraries instead of writing logic yourself DateTime in Python, Moment.js in JavaScript, ActiveSupport::TimeZone in Ruby
- Use ISO 8601 for API
Additional Resources
This article has some good reasons to why use UTC to store Time
https://kylekatarnls.medium.com/always-use-utc-dates-and-times-8a8200ca3164
This one is to see why timezones are so complicated to manage
https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a-silver-bullet/
Where UTC might not be a good option
https://engineering.q42.nl/why-always-use-utc-is-bad-advice/