Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js 2 digit year converting wrong 4 digit year

Has anyone come across this issue with Moment.js: In Firefox using moment("6/12/15").format("M/D/YYYY h:mm:ss A") I get 6/12/1915 instead of 6/12/2015?

like image 444
Paul Avatar asked May 15 '15 14:05

Paul


People also ask

How do I change a moment date to a specific format?

Date Formatting Date format conversion with Moment is simple, as shown in the following example. moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.

Is MomentJS deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

How do you find the year in a moment?

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY , then the result will be a string containing the year. If all you need is the year, then use the year() function.

Is MomentJS still used?

Conclusion. MomentJS isn't completely gone yet. But on their website they suggest you look beyond Moment unless you fall into specific usecases. Luxon seems to be the biggest replacement for Moment that is futureproof for now.


1 Answers

When you throw a random string into moment without telling it what format it's in, it falls back on the JavaScript Date object for parsing, and the format you're passing in is not defined by the standard. That leaves you wide open to implementation-specific behavior. In this case, what you describe happens on Firefox but not on Chrome.

This has been a sufficient issue that Moment is deprecating it entirely.

To get reliable results with that string, tell Moment what format it's in:

moment("6/12/15", "M/D/YY").format("M/D/YYYY h:mm:ss A")
like image 60
T.J. Crowder Avatar answered Nov 07 '22 13:11

T.J. Crowder