All Articles

3 min read • By Kyle Truong • Published 22 May 2020

Working with the JS Date object

Keeping track of date and time often involves use of the Date object and it’s a bit odd to work with compared to other types, often in unexpected ways. It tracks dates and times (datetimes) as a number representing milliseconds since January 1st 1970 UTC. It also keeps track of time internally using UTC but exposes methods that that return local time. Here are a few points about date and time that may make it easier to work with them.

Time is represented differently depending on where you’re working with. 8pm in Toronto, Canada is not the same as in Shanghai, China. This is because of timezones, or regions that observe a uniform standard time. Time in timezones is not constant. They can change for political and economic reasons, sometimes even seasonal reasons. This is why the term “offset” is sometimes used instead, because where a certain timezone may change, an offset of N hours/minutes will always be an offset of N hours/minutes (the amount of offset a region uses may still change though).

To standardize working with different timezones you may have heard of people using UTC, Coordinated Universal Time. UTC acts as a standard used around the world to keep time scales coordinated. Still, even if developers can all work in UTC, most day-to-day operations use the local time. So it may be difficult to avoid the quirks of converting between local time and UTC.

As mentioned earlier, JavaScript’s native Date object keeps track of datetimes internally using UTC but most of its methods fetch the time in the local timezone and offset (determined by the platform running the code). It may sound straightforward but I found it really odd and always got things mixed up. What helped me sort this from that was a thought:

By default, datetime input and output don’t match (timezone-wise). The Date’s input is converted to UTC but the output is in the local timezone. Outputting UTC needs to be done explicitly.

What does this mean in code?

Date.getDate()
Date.getDay()
Date.getHours()
Date.toString()

…and all of the rest of the methods all output date and time according to local time. Only by explicitly stating UTC do you get UTC:

Date.getUTCDate()
Date.getUTCDay()
Date.getUTCHours()
Date.toUTCString()

Your frontend code written for the browser can deal in local timezones out of the box but make sure you convert it back into UTC when saving it in your database and using it in your backend. If you’re looking for a library to work more in depth with the Date object, I highly recommend luxon for their great documentation and API: https://moment.github.io/luxon/docs/manual/why.html.

More on this topic:

https://medium.com/@toastui/handling-time-zone-in-javascript-547e67aa842d https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date