Convert UTC date time to local date time
Solution 1:
Append 'UTC' to the string before converting it to a date in javascript:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
Solution 2:
In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.
More info here:
- http://www.w3.org/TR/NOTE-datetime
- https://en.wikipedia.org/wiki/ISO_8601
IN this case the server would return '2011-06-29T16:52:48.000Z'
which would feed directly into the JS Date object.
var utcDate = '2011-06-29T16:52:48.000Z'; // ISO-8601 formatted date returned from server
var localDate = new Date(utcDate);
The localDate
will be in the right local time which in my case would be two hours later (DK time).
You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.
Solution 3:
This is an universal solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
Display the date based on the client local setting:
date.toLocaleString();
Solution 4:
For me above solutions didn't work.
With IE the UTC date-time conversion to local is little tricky.
For me, the date-time from web API is '2018-02-15T05:37:26.007'
and I wanted to convert as per local timezone so I used below code in JavaScript.
var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');