Skip to content Skip to sidebar Skip to footer

Moment.js Convert Local Time To Utc Time Does Work

I would like to use Moment.js to convert a local time to UTC equivalent. I believe that I have the correct method in place, but it does not alter the time. I'm in Sydney Australian

Solution 1:

I just tried this code and it seems like I get the correct UTC time. I guess I just want to confirm that what I am doing is correct way to access the UTC time from moment.js

a.format("YYYY-MM-DD HH:mm:ssZ")

"2015-03-18 04:19:46+00:00"

I found that my usage pattern of in my application was incorrect

selectedDate.utc().format(fullFormat)

It should have been

moment.utc(selectedDate).format(fullFormat)

Solution 2:

This works

moment(date_to_convert).utc().format("YYYY-MM-DD HH:mm:ss");

Solution 3:

The question is old, but I also faced it. It may be useful to someone:

Using the method of utcOffset() to calculate the UTC time:

selectedDate = (moment(selectedDate).add(-(moment().utcOffset()), 'm'));

And explicitly specify UTC:

selectedDate = moment.parseZone(selectedDate).utc().format();

Solution 4:

This worked for me !!

selectedDate = moment(selectedDate).add(moment(selectedDate).utcOffset(), 'm').utc().format()

Solution 5:

Create a local moment object from you local time and convert it to UTC then format it, then create a new UTC moment from that formatted UTC string

var localDateString = '24/04/2019';
var localDateStringFormat = 'DD/MM/YYYY';

var utcMoment = moment.utc(moment(localDateString, localDateStringFormat ).utc().format('YYYY-MM-DD HH:mm:ssZ'))

console.log(utcMoment);
<scriptsrc="https://momentjs.com/downloads/moment.js"></script>

Post a Comment for "Moment.js Convert Local Time To Utc Time Does Work"