Convert UTC date time to local date time

前端 未结 30 1031
悲哀的现实
悲哀的现实 2020-11-22 01:09

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

30条回答
  •  有刺的猬
    2020-11-22 01:32

    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.

提交回复
热议问题