Storing and Presenting Dates and Times in a Web Application

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:

  const timeZone =

      Intl.DateTimeFormat().resolvedOptions().timeZone;

We have a hidden input in the form:

  input(type="hidden" name="timezone" id="timezone")

And we store the timezone in it,

  tzInput = document.getElementById('timezone');

  tzInput.value = timeZone;

Computing the Absolute Time

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

    moment

    .tz(req.body.date, req.body.timezone)

    .tz('continent/city')

    .unix() * 1000

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:

 const date = new Date(dateString)

And format it to the local timezone as:

  date.format('DD-MM-YYYY HH:mm:ss')