Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of Sundays for next three months

Tags:

javascript

I need to get a list of Sundays for the next three months. I wrote a function which worked up until today. Three months from today is January, which is 0 so my for loop doesn't work.

function getSundays(year) {
  const offdays = [];
  let i = -1;
  const currentDate = new Date();
  currentDate.setDate(currentDate.getDate() + 90);
  for ( let month = new Date().getMonth(); month < currentDate.getMonth(); month += 1) {
    const tdays = new Date(year, month, 0).getDate();
    for (let date = 1; date <= tdays; date += 1) {
      const smonth = (month < 9) ? `0${month + 1}` : month + 1;
      const sdate = (date < 10) ? `0${date}` : date;
      const dd = `${year}-${smonth}-${sdate}`;
      const day = new Date();
      day.setDate(date);
      day.setMonth(month);
      day.setFullYear(year);
      if (day.getDay()  ===  0 ) {
        offdays[i += 1] = dd;
      }
    }
  }
  return offdays;
}

How can I get around this?

like image 481
Tom Bomb Avatar asked Nov 06 '25 01:11

Tom Bomb


1 Answers

Assuming there are about 4 Sundays per month.

function getSundays() {
    const sundays = [];
    const sunday = new Date();

    sunday.setDate(sunday.getDate() + 7 - sunday.getDay());

    for (var i = 0; i < 12; i++) {
        console.log(sunday.toLocaleString());
        sundays.push(new Date(sunday.getTime()));
        sunday.setDate(sunday.getDate() + 7);
    }

    return sundays;
}

getSundays();
like image 164
Steve Avatar answered Nov 08 '25 18:11

Steve



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!