From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM
and it is in UTC time. I want to convert it to the current user’s browser time us
function getUTC(str) {
var arr = str.split(/[- :]/);
var utc = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
utc.setTime(utc.getTime() - utc.getTimezoneOffset()*60*1000)
return utc;
}
For others who visit - use this function to get a Local date object from a UTC string, should take care of DST and will work on IE, IPhone etc.
We split the string (Since JS Date parsing is not supported on some browsers) We get difference from UTC and subtract it from the UTC time, which gives us local time. Since offset returned is calculated with DST (correct me if I am wrong), so it will set that time back in the variable "utc". Finally return the date object.
I wrote a nice little script that takes a UTC epoch and converts it the client system timezone and returns it in d/m/Y H:i:s (like the PHP date function) format:
getTimezoneDate = function ( e ) {
function p(s) { return (s < 10) ? '0' + s : s; }
var t = new Date(0);
t.setUTCSeconds(e);
var d = p(t.getDate()),
m = p(t.getMonth()+1),
Y = p(t.getFullYear()),
H = p(t.getHours()),
i = p(t.getMinutes()),
s = p(t.getSeconds());
d = [d, m, Y].join('/') + ' ' + [H, i, s].join(':');
return d;
};
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)"
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');
This is a simplified solution based on Adorjan Princ´s answer:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date);
newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return newDate;
}
Usage:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
A JSON date string (serialized in C#) looks like "2015-10-13T18:58:17".
In angular, (following Hulvej) make a localdate
filter:
myFilters.filter('localdate', function () {
return function(input) {
var date = new Date(input + '.000Z');
return date;
};
})
Then, display local time like:
{{order.createDate | localdate | date : 'MMM d, y h:mm a' }}