Photo by mariananbu on Pixabay
Photo by mariananbu on Pixabay

In an online auction project, the users were spread in a variety of time zones. Each had to see the accurate time for the end of the auction, while some users would create auctions from the web page. This required us to juggle timezones at the front-end and the backend.

Dates, Times, and Time Zones

A user of a web application has to see the dates and times in his/her local time zone. These dates and times in a SPA, or dynamically rendered parts of a we page, are obtained by JavaScript from the browser, using new Date(dateString)

This dateString comes from the server, so the question is how is it stored.

An Express Backend

Using an Express backend, we stored data in MongoDB. MongoDB store data in UTC which is an absolute unique time, no matter where MongoDB is placed and where the server is located.

Getting the Date and Time from the Web Page

The dates and times to be stored reach the server from a web form, where the user filling it can be anywhere in the world. We are just asking the user for a date and a time, so we get the time zone using JavaScript on the page with:

We have a hidden input in the form:

And we store the timezone in it,

Computing the Absolute Time

In order to get the absolute UTC time, we use Moment Time Zone,

Irrespective of where the server will be located, we decided to fix all dates and times to a specific timezone, continent/city.

Presenting Dates and Times

Using Mongoose, our controllers fetch objects from MongoDb and send them as is in the response to a request from the browser (either page navigation, or AJAX call).

We send the date string to the web page as it comes from MongoDB. At the web page we convert it to the local time zone, using Moment.js with:

And format it to the local timezone as:

Written by

Open source, Mobile, Web, Cloud, Server - Independent Information Technology and Services Professional http://yoramkornatzky.com kornatzky@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store