How To Convert UTC To Local Time Using JavaScript

Convert UTC to local time using JavaScript

To convert UTC to local time using JavaScript, You can use the toString() method, the toLocaleString() method, or create the function. Check out the details below to get more information.

Convert UTC to local time using JavaScript

Using the toString() method

The toString() is a fairly common and useful method for the developer in JavaScript. This method will return a new string from an object or an old string.

Syntax:

string.toString()

Parameter: NONE

Return value: the returns value is the content of the string.

Code example:

In this example, we use the easiest way to convert UTC to local time, and we call the toString() method and assign the result to the localTime variable.

var myUTCDate = new Date('6/29/2011 4:52:48 PM UTC');

// Using the toString method to convert myUTCDate to localTime
var localTime = myUTCDate.toString()
console.log("After converting UTC to local time: ", localTime);

Output

After converting UTC to local time: 
Wed Jun 29 2011 23:52:48 GMT+0700 

Using the toLocaleString() method

The next way is using the toLocaleString() method to convert the UTC to local time.

Example:

var myUTCDate = new Date('6/29/2011 4:52:48 PM UTC');

// Using the toLocaleString method to convert myUTCDate to localTime Canadian English
var localTime = myUTCDate.toLocaleString("en-CA")
console.log("After converting UTC to local time: ", localTime);

Output

After converting UTC to local time: 
2011-06-29, 11:52:48 p.m.

Creating the function to convert UTC to local time

Creating the function is the last way we want to introduce in this article.

  • Firstly we create the newDate by using getTime and getTimezoneOffset.
  • Then we get the timezone offset and hours of date.
  • Finally, we subtract hours and Tzoffset and set the hours of a new date.

Example:

var myUTCDate = new Date('6/29/2011 4:52:48 PM UTC');

// Create the function to convert UTC to local time
function utc2Local(date) {
	var newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);

	// Get the timezoneoffset and hours of date
	var TZoffset = date.getTimezoneOffset() / 60;
	var hours = date.getHours();

	// Setting the hours of the new date by subtracting hours and TZoffset of the date
	newDate.setHours(hours - TZoffset);
	return newDate;
}

var localTime = utc2Local(new Date(myUTCDate));
console.log("After converting UTC to local time: ", localTime)

Output

After converting UTC to local time: 
Thu Jun 30 2011 06:52:48 GMT+0700 

Summary

We have already introduced many different ways to convert UTC to local time using JavaScript but using the toString() method is very quick and comfortable. We always hope this tutorial is helpful to you.

Have a nice day, and leave your comment here if you have any questions!

Maybe you are interested:

Leave a Reply

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