Front-End 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
dateString comes from the server, so the question is how is it stored.
An Express Backend
Getting the Date and Time from the Web Page
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,
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: