Convert date to UTC using moment.js

后端 未结 11 728
囚心锁ツ
囚心锁ツ 2020-12-13 01:43

Probably and easy answer to this but I can\'t seem to find a way to get moment.js to return a UTC date time in milliseconds. Here is what I am doing:

var dat         


        
11条回答
  •  醉梦人生
    2020-12-13 02:10

    Read this documentation of moment.js here. See below example and output where I convert GMT time to local time (my zone is IST) and then I convert local time to GMT.

    // convert GMT to local time
    console.log('Server time:' + data[i].locationServerTime)
    let serv_utc = moment.utc(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
    console.log('serv_utc:' + serv_utc)
    data[i].locationServerTime = moment(serv_utc,"YYYY-MM-DD HH:mm:ss").tz(self.zone_name).format("YYYY-MM-DD HH:mm:ss");
    console.log('Converted to local time:' + data[i].locationServerTime)
    
    // convert local time to GMT
    console.log('local time:' + data[i].locationServerTime)
    let serv_utc = moment(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
    console.log('serv_utc:' + serv_utc)
    data[i].locationServerTime = moment.utc(serv_utc,"YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss");
    console.log('Converted to server time:' + data[i].locationServerTime)
    

    Output is

    Server time:2019-12-19 09:28:13
    serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
    Converted to local time:2019-12-19 14:58:13
    local time:2019-12-19 14:58:13
    serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
    Converted to server time:2019-12-19 09:28:13
    

提交回复
热议问题