Alex Neigher
Alex Neigher

Reputation: 907

Javascript date.getDay() inconsistency

I think I have found an issue in Javascript's date.getDay() function. This week, my 'day-of-the-week' (mon,tues, etc) started to be off by one in one of my applications. I have dug in further and have been able to isolate the date(s) when the date broke. I understand that getDay() returns [0-6] corresponding to [sun-sat]. However, it is returning 5 for both March 31, 2015 and April 1, 2015. Anyone have any insight as to why? My date object looks like both:

var date = new Date('2015','02','31');

and

var date = new Date('2015','03','01');

The alert you see is

alert(date.getDay());

See screenshots below for example enter image description here enter image description here

EDIT: See Fiddle

Upvotes: 0

Views: 164

Answers (1)

Johannes Reuter
Johannes Reuter

Reputation: 3547

The month is expressed by numbers from 0-11.

From https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date

month Integer value representing the month, beginning with 0 for January to 11 for December.

The error appears because the initializing of the date-object is wrong - its initialized like that: new Date('2015','04','01');, which is the first of may, and new Date('2015','03','31'); which is the 31st of april, a day that doesnt exist, so JS does the best of it and takes the day after the 30th of april, 1st of may

Upvotes: 3

Related Questions