CaptainMorgan
CaptainMorgan

Reputation: 1253

What date format to use in moment.js?

I'm using moment.js to get a UTC date offset.

I have the following code, which gives me the offset, but I get the warning "Deprecation warning: moment construction falls back to js Date".

var s = booking.booking_date_time.toString();
console.log(moment(s).parseZone(s).utcOffset());

The s variable above is set to "Mon Jun 13 2016 08:00:00 GMT+1000 (AUS Eastern Standard Time)".

I know that to get ride of the warning, I need to specify the date format in moment, but I'm not sure what the date format should be. I've tried this format "EEE MMM dd yyyy HH:mm:ss ZZ", but that doesn't work.

Upvotes: 1

Views: 1781

Answers (2)

Shrabanee
Shrabanee

Reputation: 2766

As stated in the doc:-

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, then fall back to new Date(string) if a known format is not found.

So I suggest you to use moment(new Date(booking.booking_date_time)), which will work. (If booking.booking_date_time is a valid date object)

Also refer moment-format to change to different formats supported by moment.js

Upvotes: 1

Maggie Pint
Maggie Pint

Reputation: 2452

Moment uses it's own parse token set that is not the same as other libraries. As such, you have some wrong tokens here. In addition, you need to specify that GMT is in the string, but escape it with [].

All summed up:

moment('Mon Jun 13 2016 08:00:00 GMT+1000', 'ddd MMM DD YYYY HH:mm:ss [GMT]ZZ').format()
"2016-06-12T17:00:00-05:00"

Note that when you parse using the default moment constructor, it will convert from the specified offset to the user's local time.

If you want to keep a fixed offset, use parseZone:

moment.parseZone('Mon Jun 13 2016 08:00:00 GMT+1000', 'ddd MMM DD YYYY HH:mm:ss [GMT]ZZ').format()
"2016-06-13T08:00:00+10:00"

Edit: Pay attention to the comment. If it's a date, just pass it in directly. I should have noticed that.

Upvotes: 2

Related Questions