Moment.js Convert Local time to UTC time does work

2019-02-13 22:05发布

问题:

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 +11 and expect the UTC time to be 11 hours earlier.

Internally on the moment object the isUTC flag changes from false to true, but the time does NOT shift, am I meant to use a different technique for this.

How do I actually get the current UTC date out of this object

Before Conversion

var val = '18/03/2015';
var selectedDate = moment(val, 'DD/MM/YYYY');

After Conversion

var a = selectedDate.utc()

回答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")

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)


回答2:

This worked for me !!

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


回答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();


标签: momentjs