hofnarwillie
hofnarwillie

Reputation: 3660

Moment.js creates a new date incorrectly

I have the following line of javascript using MomentJS

var date = moment('20/04/20000', 'DD/MM/YYYY'); //notice year twenty thousand
alert(date.format()); // alerts "2000-04-20T00:00:00+01:00"

If I change the format to DD/MM/YYYYY it works as expected, except of course if I enter a 6 digit year. I know this is arbitrary, but it bothers me. How do I use a format that will expect any amount of digits in the year?

Upvotes: 2

Views: 458

Answers (1)

Travis Collins
Travis Collins

Reputation: 4020

It looks like moment ignores any extra format specfiers. So you can just use as many Y's as you expect you'll need for your max date. For example this code tells moment to expect 10 digit years:

moment('20/04/20000', 'DD/MM/YYYYYYYYYY').format();

but it's return value looks like what you're expecting, 5 digit year:

"20000-04-20T00:00:00-04:00"

This is not a documented feature, and I'd be very careful about this code as you use future moment updates. Protect this code with unit tests for sure.

Upvotes: 1

Related Questions