Moment.js gives Invalid date in Firefox
Asked Answered
M

3

21

I have a requirement to convert date time in moment.js. But it gives me different result in Chrome and Firefox.

In Google Chrome it gives correct result but in Mozilla firefox gives "Invalid date".

Google chrome

moment('2016-Jan-02 02:00 AM').format()
Output: "2016-01-02T02:00:00+05:30"

Mozilla firefox

moment('2016-Jan-02 02:00 AM').format()
"Invalid date"

Your help is much appreciated.

Medievalism answered 31/12, 2015 at 4:52 Comment(0)
M
32

It's recommended to avoid using moment parsing with custom format. As the documentation states:

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

In your case, the code for consistent parsing will be:

moment('2016-Jan-02 02:00 AM', 'YYYY-MMM-DD HH:mm A')
Melodramatic answered 31/12, 2015 at 11:3 Comment(0)
F
5

You're not specifying a format for parsing the string 2016-Jan-02. So moment falls back to the native Date object, which is inconsistent across the different browsers. To parse the date consistently, include a format string along with it.

e.g.

moment("2016-Jan-02", "DD-MMM-YYYY")

Then if you want to format the moment object as a string, you can do what you were doing before:

moment("2016-Jan-02", "DD-MMM-YYYY").format("DD-MM-YYYY")

which returns the string 02-01-2016 in both browsers.

Faunie answered 6/12, 2018 at 5:4 Comment(1)
Didnt helped. If i do: moment("2016-Jan-02", "DD-MMM-YYYY").format("DD-MM-YYYY") i get Invalid date for both Chrome and Firefox...Rootlet
S
0

You need to specify input date format inside moment

moment("input_date_string", "format_of_input_date_string").format("format_of_output_date_string")

eg:

moment("27-06-2022", "DD-MM-YYYY").format("YYYY-MM-DD")

output: 2022-06-27

Samp answered 27/6, 2022 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.