Convert date to UTC using moment.js
Asked Answered
W

15

136

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?

War answered 25/4, 2014 at 17:59 Comment(0)
I
138

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();
Imaginable answered 26/4, 2014 at 1:31 Comment(7)
Edited - removed "easily". :)Imaginable
And if I already have a moment date-time with a timezone, how can I convert it to UTC?Topgallant
@Alexander - .utc()Imaginable
That doesn't work. That only changes the methods used on the date, not the date itself.Coulter
@Coulter - yes, but one would usually then call one of those methods, such as .format(), which would emit the UTC value. It can't change the internal date value itself, because a Date is already tracking a UTC timestamp. It's always just the methods called on it that determines whether to emit UTC or local time. Moment is the same in that regard.Imaginable
use moment.utc(anotherMomentDate)Weymouth
Why is it so important to read in its entirety?Hoebart
S
85

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

moment.utc(yourDate).format()
Spree answered 25/1, 2017 at 12:25 Comment(3)
This works as per documentation. converts local time to UTC.Monterrey
There's something fishy here. I'm using moment.js ver. 2.17.1 and if 'yourdate' is to '2017-10-14T21:00:00Z' (en-us) then the above snippet returns the exact same result '2017-10-14T21:00:00Z' which obviously it's not utc since I'm in gmt+3. The correct result would be '2017-10-15T00:00:00+03:00' and you get this via 'moment(yourDate).format()'.Phyllotaxis
"moment": "^2.29.1", -> this works for me ---> moment().utc().format()Oak
S
27

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

Schumann answered 25/7, 2019 at 21:23 Comment(1)
If input is in UTC, var s = new moment("2019-06-24T09:00", "YYYY-MM-DDTHH:mm").utc(); is the correct way to read. Further calls s.format() will convert it to local time.Quadrireme
K
8

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
Kyongkyoto answered 7/5, 2020 at 17:57 Comment(0)
C
4
moment.utc(date).format(...); 

is the way to go, since

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

does behave weird...

Cicerone answered 6/6, 2017 at 8:43 Comment(2)
Could you please elaborate the weird behavior of moment().utc(date).format(...)?Bareheaded
The behaviour is not weird, those are different methods. The first moment.utc(date) is for parsing the date. The second moment().utc(date) is for manipulating the current time (moment()) and the date parameter is useless since this .utc() in this case doesn't expect any params.Prose
E
4

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
Ellery answered 23/10, 2020 at 10:20 Comment(0)
B
2

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.
Buckjump answered 30/1, 2017 at 20:4 Comment(1)
This doesn't work. What does work is setting the keepOffset parameter to true, as in moment(timestamp).toISOString(true),Trinidad
E
2

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

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

Encircle answered 8/12, 2020 at 14:34 Comment(0)
O
2

This works in my case.

Library: "moment": "^2.29.1",

moment().utc().format()
Oak answered 12/7, 2022 at 20:51 Comment(0)
S
1

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);
Sagacity answered 13/5, 2019 at 13:30 Comment(0)
F
1

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
Foxworth answered 19/12, 2019 at 9:46 Comment(0)
R
1

This worked for me:

const localtime = 1622516400000
moment(localtime).utc(true).format()
Rattler answered 30/6, 2021 at 0:12 Comment(1)
I don't think this is what the author is asking This will take out the time zone information and actually modify the localtime............Volplane
V
1

We can get 2 UTC date formats.

const date = '2021-07-20T18:30:00Z';
moment.utc(moment(date).utc()).format(); // 2021-07-19T18:30:00Z
moment.utc(moment(date).utc()).toISOString(); // 2021-07-20T18:30:00.000Z (Complete ISO-8601)
Valuator answered 8/8, 2022 at 12:41 Comment(0)
D
1

Try

moment(date, format).utc().format(desireFormat)

for Example

moment('20-05-2020 10:12:44 PM', 'DD-MM-YYYY hh:mm:ss A').utc().format('YYYY-MM-DD hh:mm:ss A')
Debbydebee answered 20/4, 2023 at 22:40 Comment(0)
M
-1

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();
Moskowitz answered 12/7, 2018 at 21:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.