Javascript: Convert UTC time to local time and vice versa

Last updated on March 19, 2022 A Goodman Loading... Post a comment

This concise article shows you how to convert UTC date-time into local date-time and turn local date-time into UTC date-time in Javascript.

UTC Time to Local Time

Using Date.toLocaleString() method

Example:

// the input is in ISO-8601 format
var utcDate = "2022-03-19T20:15:50.000Z";
var localDate = new Date(utcDate).toLocaleString("en-US", {
  localeMatcher: "best fit",
  timeZoneName: "short"
});

console.log(localDate);

Output:

3/19/2022, 1:15:50 AM GMT-7

Note that the output depends on the user’s location.

Another example:

var utcDate = new Date(Date.UTC(2022, 3, 19, 8, 20, 49));
var localDate = utcDate.toLocaleString("en-US", {
  dateStyle: "full",
  timeStyle: "full"
});

console.log(localDate);

Output:

Tuesday, April 19, 2022 at 1:20:49 AM Pacific Daylight Time

Using getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds()

Example:

var utcDate = new Date(Date.UTC(2022, 03, 19, 17, 39, 49));

// Get local year, month, date, hour, minute, and second
console.log('Year:', utcDate.getFullYear());
console.log('Month:', utcDate.getMonth());
console.log('Date:', utcDate.getDate());
console.log('Hour:', utcDate.getHours());
console.log('Minute:', utcDate.getMinutes());
console.log('Second:', utcDate.getSeconds());

// Create a local date object in case you need to perform some operations
var localDate = new Date(
   utcDate.getFullYear(),
   utcDate.getMonth(),
   utcDate.getDate(),
   utcDate.getHours(),
   utcDate.getMinutes(),
   utcDate.getSeconds()
);

A user with the PDT time zone (Pacific Daylight Time) will get this result:

Year: 2022
Month: 3
Date: 20
Hour: 12
Minute: 39
Second: 49

Local Time to UTC Time

Using toISOString() method

Example:

var localDate = new Date();
console.log(localDate.toISOString());

Here’s my output:

2022-03-19T17:25:52.781Z

Your output depends on your location and when you run the code.

Using getUTCFullYear(), getUTCMonth(), getUTCDate(), getUTCHours(), getUTCMinutes(), getUTCSeconds()

Example:

var localDate = new Date();

 var utcDate = new Date(
        Date.UTC(
          localDate.getUTCFullYear(),
          localDate.getUTCMonth(),
          localDate.getUTCDate(),
          localDate.getUTCHours(),
          localDate.getUTCMinutes(),
          localDate.getUTCSeconds()
        )
);

// do something with your utcDate object

Final Words

You’ve learned some techniques to turn UTC date into local date and vice versa in vanilla Javascript. If you’d like to explore more new and interesting things about this programming language, take a look at the following articles:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles