Convert UTC date time to local date time

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

    I've created one function which converts all the timezones into local time.

    I did not used getTimezoneOffset(), because it does not returns proper offset value

    Requirements:

    1. npm i moment-timezone
    
    function utcToLocal(utcdateTime, tz) {
        var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
        var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
        var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
        var localDateTime
        var hours = zoneValue.split(":")[0]
        var minutes = zoneValue.split(":")[1]
        if (operator === "-") {
            localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
        } else if (operator) {
            localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
        } else {
            localDateTime = "Invalid Timezone Operator"
        }
        return localDateTime
    }
    
    utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
    
    //Returns "2019-11-14 12:45:37"
    

提交回复
热议问题