Like in our daily lives, the date plays a significant role in any type of application. For example, let’s consider a blog website. Timestamps are used to denote blog publish date, last edit date, comment date, and more.
If you want today’s date, you can simply write the following line. This will give you a new object with the current date and time, in your specific timezone.
const d = new Date()
Sat May 02 2020 14:27:09 GMT+0530
So, inputting a date in your timezone is pretty straightforward. However, managing dates and times gets trickier if you have to display different dates for different countries or cities. For example, an alert functionality may need to get triggered at 16:00 hours every day, in the client's specific time zone.
We can solve this problem in simple 5 steps.
- Convert the Date into msec since Jan 1, 1970.
- Obtain local UTC offset and convert to msec.
- Obtain the current UTC time, by adding the local time zone offset to the local time.
- Obtain the destination city’s UTC offset in hours, convert it to milliseconds and add it to UTC time.
- Convert final msec value into new Date string.
Quite simple, isn’t it? But there is one more consideration to keep in mind. Namely: will time zone offset adjust when Daylight Saving Time is in effect? The answer is Yes.
If we are considering New York, USA, then during Daylight Saving, the offset is -4, whereas it would otherwise be -5.
There’s a solution for this as well: an additional function while obtaining destination city’s UTC offset. This function will determine if Daylight Saving is in effect (or not), and then return the offset accordingly.
Here’s the code to convert the Date in a different timezone with the Daylight Saving check.
You can see that the transformed Date object will show local offset; that’s because we have created a new Date object with our result msec value. If you look at the Date and Time, you can see the difference.