Ashwin
Ashwin

Reputation: 12421

date object returns random date for invalid months/day

This code:

var dt = new Date('82/66/2005');

...gives a value for dt as Wed Nov 25 1992 00:00:00 GMT+0530 (IST) on Firefox.

How?

Fiddle - http://jsfiddle.net/4jyT3/1/

Upvotes: 0

Views: 293

Answers (2)

Paul S.
Paul S.

Reputation: 66334

I can't re-produce this in Chrome, but I'll explain how FireFox arrives here.

new Date('82-66-2005');

Invalid date, let's guess what you wanted based on what we know about dates.

  • hyphen - format is usually yyyy-mm-dd
  • yy is short for 19yy
  • there are 12 months, so month 13 is Januaray of next year
  • similarly for days

So using this knowledge lets estimate it, assuming 365.25 days per year and 30.5 days per month.

// input
var year = 1982, // 19yy
    bigMonth = 66,
    bigDay = 2005;

// adjust day for years
var day = bigDay % 365.25;
year = year + (bigDay - day) / 365.25;

// adjust day for months
bigDay = day;
day = bigDay % 30.5;
bigMonth = bigMonth + (bigDay - day) / 30.5;

// adjust month for years
var month = bigMonth % 12;
year = year + (bigMonth - month) / 12;

console.log(year, month, day); // 1992 11 26.25

So it would be about the Nov 26th, 1992, which is pretty close to how your browser calculated it (it didn't need to estimate).

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074535

That date is not in a format that is specified to be supported by the Date constructor. I'm not surprised to find that most engines call it invalid, but apparently Firefox is attempting to make a date out of that. Even though it's not specified, most engines support month/day/year and all, last I checked, support year/month/day. Firefox appears to be applying year/month/day to the input, where most browsers see the invalid values and go with "invalid."

So Firefox is seeing 82 for year (and assuming 1982), 66 for month, and 2005 for day. JavaScript is usually very forgiving about out-of-bound values on dates, moving to the next month and such as necessary. And that's what's happening here: If you take January 1st 1982 and add a further 65 months and 2004 days, you end up on Nov 25 1992.

This code will reliably give you the date you mentioned:

var dt = new Date(1982, 65, 2005);

(65 instead of 66 because in the number form, months start with 0, but in string form, they start with 1.)

Upvotes: 1

Related Questions