首页 > 解决方案 > 获取未来三个月的周日列表

问题描述

我需要得到一份未来三个月的周日清单。我写了一个一直工作到今天的函数。从今天开始的三个月是一月,它是 0,所以我的 for 循环不起作用。

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;
}

我怎样才能解决这个问题?

标签: javascript

解决方案


你可以使用 Date get|setMonth 和 get|setDay 的方法,就像这样:

const next = new Date()
next.setMonth( (new Date()).getMonth()+1 )

const allSundays = []
const sundaysByMonth = []

for( let i = 0; i<3; i++ ){

    const m = next.getMonth()
    
    const sundays = []
    for( let j = 0; j < 7; j++ ){
    	
    	if ( next.getDay() == 0 ){
            sundays.push( next.getDate() )
            allSundays.push( next.getDate() )
            next.setDate( next.getDate() + 6 )  // increment in 6 days not 7 (one week) because line below increase again
        }
        
        next.setDate( next.getDate() + 1 ) // increase month day until arrive in sunday
        if( next.getMonth() != m ){ // check if not exceeded the month
        	sundaysByMonth.push( sundays )
          	break // break to go to next month
        }
        
    }
}

console.log( allSundays )
console.log( sundaysByMonth )
const el = document.getElementById("demo");

for( let i = 0; i < allSundays.length; i++ ){
  const li = document.createElement('li')
  li.innerHTML = 'Sunday '+ allSundays[i]+' '
  el.appendChild(li)
}
<p>The getDay() method returns the weekday as a number:</p>

<ul id="demo"></ul>


推荐阅读