Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function return date array for all Sundays in a year

Tags:

javascript

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?

like image 764
S.Sid Avatar asked Sep 03 '26 14:09

S.Sid


1 Answers

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 month property of the Date object is zero based, not one based. If you change this line, the function will return the correct dates:

day.setMonth(month - 1);

Also, the loop only runs from 1 to 11, you need to include december too:

for (month=1; month <= 12; month++)

Another way to do this would be to find the first sunday, then just step forward seven days at a time:

function getDefaultOffDays2(year) {
  var date = new Date(year, 0, 1);
  while (date.getDay() != 0) {
    date.setDate(date.getDate() + 1);
  }
  var days = [];
  while (date.getFullYear() == year) {
    var m = date.getMonth() + 1;
    var d = date.getDate();
    days.push(
      year + '-' +
      (m < 10 ? '0' + m : m) + '-' +
      (d < 10 ? '0' + d : d)
    );
    date.setDate(date.getDate() + 7);
  }
  return days;
}
like image 168
Guffa Avatar answered Sep 06 '26 03:09

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!