When asked if they struggle with handling dates and timezones, more than 50% of developers responded "YES". My guess is that the people who said "NO" to this poll either have it figured out already, or they don't work with platforms/apps that have to cater to users across the globe.
Anyway, I wanted to create a blog post that goes into some detail on how I handle dates and timezones. I think by following these simple rules, it can be a lot less of a headache for you.
Rule #1 - STORE DATETIMES IN UTC IN YOUR DATABASE, AND BACK END CODE. It is important that there is consistency across all your date-related data. When storing dates in the database, they should always be in UTC. If you are not familiar with what UTC is, it is a primary time standard that all the major timezones are based on. The major timezones are just offsets from UTC. Furthermore, make sure the datetime is in UTC when you're handling it with your backend code.
Rule #2 - CONVERT DATETIMES TO THE USER'S LOCAL TIMEZONE USING FRONTEND CODE. Although your backend will be returning UTC times, the frontend can easily convert these to the user's local timezone. Doing this instills a separation of duties between the backend (handle in UTC) and the frontend (handle in the user's local time). Stay consistent with the format of your date times in the frontend by using a standard, such as ISO 8601. When you send requests to the backend, send the datetime in ISO 8601 format so that the backend can easily convert it to the corresponding UTC date time.
By following these rules, you should instill an efficient PROCESS in how you handle datetimes.
- UTC Time Standard - https://en.wikipedia.org/wiki/Coordinated_Universal_Time
- ISO 8601 Time Format Standard - https://en.wikipedia.org/wiki/ISO_8601
- Moment JS datetime library - https://momentjs.com/
- Carbon PHP datetime library - https://carbon.nesbot.com/docs/