Convert date to UTC using moment.js

后端 未结 11 730
囚心锁ツ
囚心锁ツ 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:04

    here, I'm passing the date object and converting it into UTC time.

    $.fn.convertTimeToUTC = function (convertTime) {
       if($(this).isObject(convertTime)) {
            return moment.tz(convertTime.format("Y-MM-DD HH:mm:ss"), moment.tz.guess()).utc().format("Y-MM-DD HH:mm:ss");
        }
    };
    // Returns if a value is an object
    $.fn.isObject =  function(value) {
        return value && typeof value === 'object';
    };
    
    
    //you can call it as below
    $(this).convertTimeToUTC(date);
    
    0 讨论(0)
  • 2020-12-13 02:09

    This moment.utc(stringDate, format).toDate() worked for me.

    This moment.utc(date).toDate() not.

    0 讨论(0)
  • 2020-12-13 02:10

    I use this method and it works. ValueOf does not work for me.

    moment.utc(yourDate).format()
    
    0 讨论(0)
  • 2020-12-13 02:10

    If all else fails, just reinitialize with an inverse of your local offset.

    var timestamp = new Date();
    var inverseOffset = moment(timestamp).utcOffset() * -1;
    timestamp = moment().utcOffset( inverseOffset  );
    
    timestamp.toISOString(); // This should give you the accurate UTC equivalent.
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题