Convert date to UTC using moment.js

JavascriptMomentjs

Javascript Problem Overview


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 date = $("#txt-date").val(),
    expires = moment.utc(date);

Any idea what I am doing wrong?

Javascript Solutions


Solution 1 - Javascript

This is found in the documentation. With a library like moment, I urge you to read the entirety of the documentation. It's really important.

Assuming the input text is entered in terms of the users's local time:

 var expires = moment(date).valueOf();

If the user is instructed actually enter a UTC date/time, then:

 var expires = moment.utc(date).valueOf();

Solution 2 - Javascript

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

moment.utc(yourDate).format()

Solution 3 - Javascript

As of : moment.js version 2.24.0

let's say you have a local date input, this is the proper way to convert your dateTime or Time input to UTC :

var utcStart = new moment("09:00", "HH:mm").utc();

or in case you specify a date

var utcStart = new moment("2019-06-24T09:00", "YYYY-MM-DDTHH:mm").utc();
 

As you can see the result output will be returned in UTC :

//You can call the format() that will return your UTC date in a string 
 utcStart.format(); 
//Result : 2019-06-24T13:00:00 
    

But if you do this as below, it will not convert to UTC :

var myTime = new moment.utc("09:00", "HH:mm"); 

You're only setting your input to utc time, it's as if your mentioning that myTime is in UTC, ....the output will be 9:00

Solution 4 - Javascript

This will be the answer:

moment.utc(moment(localdate)).format()
localdate = '2020-01-01 12:00:00'

moment(localdate)
//Moment<2020-01-01T12:00:00+08:00>

moment.utc(moment(localdate)).format()
//2020-01-01T04:00:00Z

Solution 5 - Javascript

moment.utc(date).format(...); 

is the way to go, since

moment().utc(date).format(...);

does behave weird...

Solution 6 - Javascript

This worked for me. Others might find it useful.

let date = '2020-08-31T00:00:00Z'
moment.utc(moment(date).utc()).format() // returns 2020-08-30T22:00:00Z

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

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

Solution 9 - Javascript

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);

Solution 10 - Javascript

This worked for me:

const localtime = 1622516400000
moment(localtime).utc(true).format()

Solution 11 - Javascript

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

Solution 12 - Javascript

Don't you need something to compare and then retrieve the milliseconds?

For instance:

let enteredDate = $("#txt-date").val(); // get the date entered in the input
let expires = moment.utc(enteredDate); // convert it into UTC

With that you have the expiring date in UTC. Now you can get the "right-now" date in UTC and compare:

var rightNowUTC = moment.utc(); // get this moment in UTC based on browser
let duration = moment.duration(rightNowUTC.diff(expires)); // get the diff
let remainingTimeInMls = duration.asMilliseconds();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1956816View Question on Stackoverflow
Solution 1 - JavascriptMatt Johnson-PintView Answer on Stackoverflow
Solution 2 - JavascriptBruno QuaresmaView Answer on Stackoverflow
Solution 3 - Javascriptnapi15View Answer on Stackoverflow
Solution 4 - JavascriptsoohanView Answer on Stackoverflow
Solution 5 - JavascriptFlorian SView Answer on Stackoverflow
Solution 6 - JavascriptMikaelView Answer on Stackoverflow
Solution 7 - JavascriptTimothy PerezView Answer on Stackoverflow
Solution 8 - JavascriptHizabrView Answer on Stackoverflow
Solution 9 - JavascriptInvincibleView Answer on Stackoverflow
Solution 10 - JavascriptcfcmView Answer on Stackoverflow
Solution 11 - JavascriptdineshydvView Answer on Stackoverflow
Solution 12 - JavascripttheRonnyView Answer on Stackoverflow