alek alek - 6 months ago 24
Javascript Question

moment.js issue on firefox

This code works fine on chrome but does not work on firefox or IE.
Note that it works fine when I remove the "+00:00"

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.0/moment.min.js"></script>
<script>
var now = moment("Sun Jun 01 2016 05:00:00+00:00").format('ddd MMM DD YYYY HH:mm:ssZ');
alert(now);
</script>

Answer

If you don't pass the format of the string to parse, you're relying on moment.js guessing the format and if it can't get something that looks like a valid date (it may still be incorrect), it will fall back to parsing by the built–in Date constructor, which is strongly recommended against. The format method is for the output format, not the parse format.

To pass the format of the string to the moment.js parser, include it as the second argument:

moment("Sun Jun 01 2016 05:00:00+00:00",'ddd MMM DD YYYY HH:mm:ssZ').format(/*output format*/)

Note also that where it falls back to built–in parsing, the following warning is displayed in the console:

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.

Comments