DEV Community

Cover image for How to handle date, date time and timezone in API, UI, Database
Mandar Badve
Mandar Badve

Posted on

How to handle date, date time and timezone in API, UI, Database

Handling date, date time and timezone is very difficult part of coding. Especially if your application is going to be access across countries from different regions.
It’s always painful to modify your code to support multiple time zones after production deployment. So before going it to production I need help.
Please share the standard technique to handle date and date time through out application i.e. at API, at UI and at Database level

Top comments (4)

Collapse
 
xngwng profile image
Xing Wang • Edited

Agreed. At database level (or even backend, e.g. your restful API) do everything in UTC or epoch time (which is just an integer in milliseconds since Epoch time (00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.)). Either epoch time or UTC time is fine.

At UI level (i.e. clientside), where you have the timezone of the user (which you can get from the system, either inside browser or mobile app), convert to to localTime before you display it.

Because of that, in most cases, you don't really needs to store the timezone of the user. Unless you plan to send email or something from backend that you want to show the time based on the localTime of the user. Then you may want to store the timezone of the user in his user profile. And only need convert to the user's localTime right before you sent out the email.

Collapse
 
sadarshannaiynar profile image
Adarsh

I would suggest converting it into UTC format and storing it in database and whenever you retrieve you can pass the appropriate locale and get the date and time in that locale.

Collapse
 
courier10pt profile image
Bob van Hoove • Edited

This video may be of interest:

Jon Skeet - Working with time is easy

(Edit) Or if you prefer to read:

What's wrong with DateTime anyway

Collapse
 
sudiukil profile image
Quentin Sonrel

I don't know what are the best practices when it comes to this to be honest, but when I need to deal with dates and times in my projects I usually work with UTC on the backend side and convert everything on the frontend side.