Reputation: 81
I have to write function which determines which day of week particular date is. I wrote following code, but it returns in 99% cases wrong day. Can you explain me why?
var day = 1, month = 1, year = 2016;
function whatDay(day, month, year) {
var myDate = new Date();
myDate.setFullYear(year);
myDate.setMonth(month);
myDate.setDate(day);
console.log( myDate.getDay() );
}
whatDay(day, month, year);
Upvotes: 1
Views: 169
Reputation: 172608
I guess you are confused as to how the getDay works. See the docs:
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
So the day starts from 0 index representing Sunday. 1 as Monday and so on based on the local time.
Just to add, that similarly the months are also indexed from 0. So 0 is for January and so on.
Upvotes: 3
Reputation: 50346
which day of week particular date
It seems you are looking for weekday like Sunday,Monday & so on.+
If it is so then following snippet can be useful
var day = 1, month = 1, year = 2016;
function whatDay(day, month, year) {
var myDate = new Date();
myDate.setFullYear(year);
myDate.setMonth(month);
myDate.setDate(day);
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var n = weekday[myDate.getDay()]
console.log(n); //Monday
}
whatDay(day, month, year);
Upvotes: 3
Reputation: 81
Problem solved. I know how getDay() works, however I didn't know that it counts months from 0 to 11. Thanks @Amadan
Upvotes: 0