Convert UTC date time to local date time

前端 未结 30 1512
悲哀的现实
悲哀的现实 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:47

    @Adorojan's answer is almost correct. But addition of offset is not correct since offset value will be negative if browser date is ahead of GMT and vice versa. Below is the solution which I came with and is working perfectly fine for me:

    // Input time in UTC
    var inputInUtc = "6/29/2011 4:52:48";
    
    var dateInUtc = new Date(Date.parse(inputInUtc+" UTC"));
    //Print date in UTC time
    document.write("Date in UTC : " + dateInUtc.toISOString()+"
    "); var dateInLocalTz = convertUtcToLocalTz(dateInUtc); //Print date in local time document.write("Date in Local : " + dateInLocalTz.toISOString()); function convertUtcToLocalTz(dateInUtc) { //Convert to local timezone return new Date(dateInUtc.getTime() - dateInUtc.getTimezoneOffset()*60*1000); }

提交回复
热议问题