Reputation: 4776
I have written a function to give me all days of a month excluding weekends. Every thing works fine but when I want to get December days the Date object returns 01 Jan of next week and the function returns an empty array.
Any help please.
function getDaysInMonth(month, year) {
var date = new Date(year, month-1, 1);
var days = [];
while (date.getMonth() === month) {
// Exclude weekends
var tmpDate = new Date(date);
var weekDay = tmpDate.getDay(); // week day
var day = tmpDate.getDate(); // day
if (weekDay !== 1 && weekDay !== 2) {
days.push(day);
}
date.setDate(date.getDate() + 1);
}
return days;
}
alert(getDaysInMonth(month, year))
Upvotes: 6
Views: 2872
Reputation: 1
When you create a date, you use month = 0 to 11
This also goes for when you GET the month - it also returns 0 to 11
I'm surprised you said
Every thing works fine
It actually never worked for any month - always would return an empty array
function getDaysInMonth(month, year) {
month--; // lets fix the month once, here and be done with it
var date = new Date(year, month, 1);
var days = [];
while (date.getMonth() === month) {
// Exclude weekends
var tmpDate = new Date(date);
var weekDay = tmpDate.getDay(); // week day
var day = tmpDate.getDate(); // day
if (weekDay%6) { // exclude 0=Sunday and 6=Saturday
days.push(day);
}
date.setDate(date.getDate() + 1);
}
return days;
}
alert(getDaysInMonth(month, year))
Upvotes: 7