How To Convert GMT To Local Time Using JavaScript

Convert GMT to local time using JavaScript

JavaScript offers you many methods of Date to convert GMT to local time using JavaScript, like using the toLocaleString() method and using the toLocaleDateString() method. Check out the details below to get more information.

Convert GMT to local time using JavaScript

Using the toLocaleString() method

In the first way, we will use the toLocaleString() method to convert a Date object as a string and set it to the US English time. The toLocaleString() method was introduced in the other article. Please read it here to get more information about this method. You can easily learn how to use this method through our code example below.

Code example:

In this example, we create the strDateTime variable and call the Date() method to convert the GMT time to Date object.

After that, we call the toLocaleString(‘en-US’) to convert the GMT time to US English time.

Let’s see the code example below.

var strDateTime = new Date("Fri, 20 Nov 2020 11:38:23 GMT");
console.log("Here is the UTC time: ", strDateTime);

// Using the toLocaleString() method to convert to US English
var result = strDateTime.toLocaleString('en-US');
console.log('After converting GMT to local time:', result);

Output

Here is the UTC time: Fri Nov 20 2020 18:38:23 GMT+0700
After converting GMT to local time: 11/20/2020, 6:38:23 PM

Using the toLocaleDateString() method

The next way is the toLocaleDateString() method. We are calling this method to get only the time of the GMT time. And then call the getHours(), getMinutes(), and getSeconds() to get the hours, minutes, and seconds of the GMT time.

Example:

In this example, we will use the toLocaleDateString() method to get only the Date of strDateTime variable. Then we call sequence the getHours(), getMinutes(), and getSeconds() methods to get the hours, minutes, and seconds. Finally, we add them together into the result variable and print out the result in the console. 

var strDateTime = new Date("Fri, 20 Nov 2020 11:38:23 GMT");
console.log("Here is the UTC time: ", strDateTime);

// Using the toLocaleDateString() method to convert to US English
var result = strDateTime.toLocaleDateString('en-US') + ' ' +
	strDateTime.getHours() + ':' + strDateTime.getMinutes() + ':' + strDateTime.getSeconds();

console.log('After converting GMT to local time:', result);

Output

Here is the UTC time: Fri Nov 20 2020 18:38:23 GMT+0700
After converting GMT to local time: 11/20/2020 18:38:23

Summary

Hopefully, throughout the article, you can easily find for yourself method to convert GMT to local time using JavaScript. Leave your comment here if you have any questions about this article. Thank you for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *