Sometimes, we may want to convert a UTC date-time to a local date-time in our JavaScript apps.
In this article, we’ll look at how to convert UTC date-time to local date-time.
Add UTC after the Date String and Pass the String into the Date Constructor
One way to convert UTC date time to a local date-time is to just add the 'UTC'
suffix to the date-time string.
Then we pass it into the Date
constructor.
For instance, we can write:
const date = new Date('6/29/2021 4:52:48 PM UTC');
console.log(date.toString())
Then if we’re in the Pacific Time zone, we get:
Tue Jun 29 2021 09:52:48 GMT-0700 (Pacific Daylight Time)
logged.
The conversion is done automatically to local time as we can see.
Add Z after the Date String and Pass the String into the Date Constructor
The Z
suffix is the same as UTC
for setting a date-time to UTC.
We can attach this suffix to an ISO-8601 date-time since it is part of the standard.
For instance, we can write:
const date = new Date('2021-06-29T16:52:48.000Z');
console.log(date.toString())
Then we get:
Tue Jun 29 2021 09:52:48 GMT-0700 (Pacific Daylight Time)
as a result if we’re in Pacific Time.
Call getTimezoneOffset
Method to Convert the Date Time to a Local Date Time
We can call getTimezoneOffset
on a JavaScript date offset to get the time difference UTC and the local time zone in hours.
For instance, we can write:
const date = new Date('2021-06-29T16:52:48.000');
const newDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000);
console.log(newDate)
We call getTime
to get the timestamp for the date
we want to convert.
Then we add the timezone offset in milliseconds we create with:
date.getTimezoneOffset() * 60 * 1000
Then we get the time zone offset and divide it by 60 to get the offset in hours.
And then we get:
Tue Jun 29 2021 02:52:48 GMT-0700 (Pacific Daylight Time)
as a result.
Conclusion
We can convert a UTC date-time into a local date-time with various date methods.