JavaScript allows you to work with dates are strings as well as objects. But we have to be careful while interchanging dates into string and vice versa since web browsers convert strings to date objects as per local time zone, by default. Sometimes you may need to convert UTC date time to local date time in JS. In this article, we will learn how to do this.
How to Convert UTC Date Time to Local Date Time in JS
There are two ways to represent date strings as UTC date time.
var date_string = '6/29/2011 4:52:48 PM UTC'; OR var date_string = '2011-06-29T16:52:48.000Z'
In both these cases, you just need to pass them into Date() constructor to obtain a date object as per local time zone.
var localDate = new Date(date_string);
Thereafter, if you want to display date as a string, use toLocaleString() function.
console.log(date.toLocaleString());
While working with UTC date time, make sure that UTC datetime string has either Z or UTC suffix. This will allow the strings to be parsed correctly. If they are not present in your date string, please add it, before you proceed further.
var date_string = "2011-06-29T16:52:48"; var localDateTime = new Date(datetime + 'Z');
In this short article, we have learnt how to convert UTC time to local date time.
Also read:
How to Use Variable Number of Arguments in JS Function
How to Add 1 Day to Current Date
How to Change One Character in Python String
How to Permanently Add Directory to Python Path
How to Install Python Package Using .whl file
Related posts:
How to Merge Two JS Objects
How to Use Variable As Key in JavaScript Object
How to Add 30 Minutes to JS Date Object
How to Use Variable Number of Arguments in JS Function
How to Persist Variables Between Page Load
How to Find DOM Element Using Attribute Value
How to Display Local Storage Data in JavaScript
How to Check if Variable is Array in JavaScript

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.