Question

moment("05/1/11").toString() returns "Mon May 01 1911" not 2011 as expected.

In Moment.js documentation I see "2 digit year (if greater than 68 will return 1900's, otherwise 2000's)" multiple times (for year, week, and ISO year).

I would expect moment to follow this by default when parsing a date without a format, but it doesn't. Is this a feature? Is there a way to force it to behave this way (2000 if less than 68) for years anyway?

I need to parse free-form user input. It might be 5/1/11 it may be July 5 11 or July 6, 2011. So the only format I wish to pass into to moment is for the years field, and then only if a four-digit year is not found in user input.

Était-ce utile?

La solution

If you don't specify a format string, the parsing is handled by the browser (i.e. new Date(string)), not by Moment; see the documentation for moment(string) in the docs. If you want Moment to do the parsing (and apply rules like > 68), you need to provide the format string.

var test = moment("05/1/11", "MM/D/YY").toString();
$('#date').append(test);

http://jsfiddle.net/WBDDc/

Output:

Sun May 01 2011 00:00:00 GMT-0400

Autres conseils

from Momentjs docs

Parsing two digit years By default, two digit years above 68 are assumed to be in the 1900's and years 68 or below are assumed to be in the 2000's. This can be changed by replacing the moment.parseTwoDigitYear method. The only argument of this method is a string containing the two years input by the user, and should return the year as an integer.

you can use this code to configure how moment will parse two year string

   moment.parseTwoDigitYear = function (yearString) {
        return parseInt(yearString) + (parseInt(yearString) > 19 ? 1900 : 2000);
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top