Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Year in moment JS defaults to 1900 instead of 2000?

Tags:

momentjs

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.

like image 478
gort Avatar asked Feb 25 '14 18:02

gort


People also ask

How do you switch to UTC mode in MomentJs?

Any moment created with moment. utc() will be in UTC mode, and any moment created with moment() will not. To switch from UTC to local time, you can use moment#utc or moment#local.

Is MomentJs being deprecated?

MomentJs recently announced that the library is now deprecated. This is a big deal for the javascript community who actively downloads moment almost 15 million times a week. With that I began a journey during a Hackathon to replace moment in a core library at my company.

How do you find the current year using moments?

The moment(). year() method is used to get or set the year of the Moment object. The year value that can be set has a range from -270,000 to 270,000.


1 Answers

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
like image 75
Engineer2021 Avatar answered Oct 01 '22 09:10

Engineer2021