i am writing a function in javascript that will return date array of all sundays.
below you can see my code :
function getDefaultOffDays(year){
var offdays=new Array();
i=0;
for(month=1;month<12;month++)
{
tdays=new Date(year, month, 0).getDate();
for(date=1;date<=tdays;date++)
{
smonth=(month<10)?"0"+month:month;
sdate=(date<10)?"0"+date:date;
dd=year+"-"+smonth+"-"+sdate;
day=new Date();
day.setDate(date);
day.setMonth(month);
day.setFullYear(year);
if(day.getDay() == 0 )
{
offdays[i++]=dd;
}
}
}
return offdays;
}
the issue is that the returned array is giving random dates not the only dates for sunday 🙁
m i missing some thing?
If you examine the result, you can see that it’s actually not random. It returns the dates for january that are sundays in february, and so on.
The
monthproperty of theDateobject is zero based, not one based. If you change this line, the function will return the correct dates:Also, the loop only runs from 1 to 11, you need to include december too:
Another way to do this would be to find the first sunday, then just step forward seven days at a time: