获取接下来三个月的星期日清单

时间:2018-11-01 03:20:11

标签: javascript

我需要获得接下来三个月的星期日清单。我编写了一个功能,直到今天。从今天开始的三个月是一月,它是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;
}

我该如何解决?

5 个答案:

答案 0 :(得分:0)

请在下面测试代码。

var startDate = new Date(2018, 0, 1);
var endDate = new Date(2018,11, 31);
var day = 0;  
for (i = 0; i <= 7; i++) { 
    if(startDate.toString().indexOf('Sun') !== -1){
       break;
    }
    startDate =  new Date(2018, 0, i);
}

var result = [];
startDate = moment(startDate);
endDate = moment(endDate);
var current = startDate.clone();
while (current.day(7 + day).isBefore(endDate)) {
  result.push(current.clone());
}

//console.log(result.map(m => m.format('LLLL')));
console.log(result.map(m => m.format('YYYY-MM-DD')));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

答案 1 :(得分:0)

假设每月大约有四个星期日。

function getSundays() {
    const sundays = [];

    var 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();

答案 2 :(得分:0)

如果您想要基于非Momentjs的方法,也许您可​​以做这样的事情?

此方法一次增加一天,从未来开始连续三个月,并查找getDay() === 0(即星期日)的任何日期实例。

通过milliseconds完成增量操作,这是为特定日期/月份/年份创建日期对象的便捷方法。月计数器跟踪currentDatenextDate之间的月/年变化,以确定是否应增加月计数器:

function getSundays(year) {
  
  var start = new Date();
  start.setYear(year);
  var startEpoch = start.valueOf();
  
  var dayDuration = 86400000; // Milliseconds in a day
  var currentEpoch = startEpoch;
  
  var offdays = [];
  
  // Iterate over three month period from as required
  for(var monthCounter = 0; monthCounter < 3; ) {
  	
    var currentDate = new Date(currentEpoch);
    var nextDate = new Date(currentEpoch + dayDuration);
    
    // If the next month or next year has increased from 
    // current month or year, then increment the month counter
    if(nextDate.getMonth() > currentDate.getMonth() || 
    nextDate.getYear() > currentDate.getYear()) {
    	monthCounter ++;
    }
  	
    if(currentDate.getDay() === 0) {
    	offdays.push(currentDate);
    }
    
    currentEpoch += dayDuration;
  	
  }
  
  return offdays;
}

console.log(getSundays(2018).map(date => date.toString()));

答案 3 :(得分:0)

您可以使用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>

答案 4 :(得分:0)

看了一些已经给出的答案,它们似乎很接近,并激发了我不用使用moment.js的机会。-评论得很重,希望能解释一下,但这对我理解问题是有用的,尽管您可能需要可以为您的目的塑造result的值,但我相信它包含了您所需要的。

function getSundaysForNextCalendarMonths(numberOfMonths, dateVal){
	let trackingObj = {};  // We'll use this object to track our trackingObjs by month in our loop.
	let result = []; // We'll just push the date from each iteration here rather than make a mapping function on the result for this example.  might be overkill anyways, this array shouldn't contain more than 15 days
	if(!dateVal){
		dateVal = new Date(); // initialize the date to today or wherever you want to start from
	}
	// Using today's date as reference the first time through the loop we find out how far off Sunday it is, and then add the difference times the time of day in milliseconds in UNIX time
	// but first - we'll also set the time to 2 AM to work around any potential daylight savings time weirdness in case the hour shifts up or down over a the period
	dateVal.setHours(2);
	dateVal.setTime(dateVal.getTime() + (7 - dateVal.getDay()) * (24*60*60*1000)); // mutated dateVal to now equal following Sunday
	result.push(dateVal.toDateString());
	// This loop in theory will break before iterates all the way through, because you'd never have 15 Sundays in a 3 month, but I removed the while loop because it's easier to ascertain the runtime of the loop
	for(let i = 0; i < numberOfMonths * 5; i++){ 
		// we just add 7 days in milliseconds to dateVal to get next Sunday
		dateVal.setTime(dateVal.getTime() + 7 * (24*60*60*1000));
		if(trackingObj[dateVal.getMonth()]) {  // If there's already a month in the reuslt, push to the array that's there.
			result.push(dateVal.toDateString());
		} else if(!trackingObj[dateVal.getMonth()] && Object.keys(trackingObj).length < numberOfMonths){  // Otherwise if there's not too many months in  the trackingObj put the object in the array
			trackingObj[dateVal.getMonth()] = true;
			result.push(dateVal.toDateString());
		} else {
			break;  // more than 3 months break loop.  you have your trackingObj
		}
	}
	return result;
}
console.log(getSundaysForNextCalendarMonths(3));

enter code here