Search code examples
javascriptinternet-explorer-10localtime

Convert UTC time to local time zone in IE in javascript


I have a date time string in format ("2015-10-07 15:20:00 UTC") and i want to convert it to local time zone of client. i am using the following statements for this:

var UTC_Time = new Date ("2015-10-07 15:20:00 UTC");

var localTime = UTC_Time.toString();

in Google Chrome it works fine and return the converted time as 2015-10-07 20:20:00 PST which is fine. But in internet explorer (i am concerned with IE10) it is returning the same UTC date i.e. 2015-10-07 15:20:00. how can i get the converted time in IE. Any help would be greatly appreciated.


Solution

  • When you display a date in javascript, it converts it to the client time. Since you are specifying UTC in your date string, it will assume that it's a UTC date. There are a couple ways you can solve this.

    If you just need a string, you can do localTime = UTC_Time.toUTCString().

    If you need a js Date object, you can create a new date object by getting the values from the previous object.

    new Date(UTC_Time.getUTCFullYear(), UTC_Time.getUTCMonth(), 
        UTC_Time.getUTCDate(), UTC_Time.getUTCHours(), UTC_Time.getUTCMinutes(), 
        UTC_Time.getUTCSeconds(), UTC_Time.getUTCMilliseconds());
    

    Or you can simply replace the UTC part of the string.

    var dtStr = "2015-10-07 15:20:00 UTC";
    dtStr = dtStr.replace(" UTC", "");
    var localTime = new Date(dtStr);
    

    Only use this option if you know your string will always be in the same format.