javascript 把接下来三个月的周日列出来

gijlo24d  于 9个月前  发布在  Java
关注(0)|答案(6)|浏览(81)

我需要得到接下来三个月的周日列表,我写了一个函数,直到今天还能工作,从今天起的三个月是一月,这是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;
}

字符串
我该怎么办?

dw1jzc5e

dw1jzc5e1#

假设每个月有4个星期天。

function getSundays() {
    let sundays = [];

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

字符串

0kjbasz6

0kjbasz62#

请测试下面的代码。

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')));

个字符

iqih9akk

iqih9akk3#

如果你想要一个不基于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()));

字符串

sqserrrh

sqserrrh4#

您可以使用Date get的方法|setMonth和get| setDay,就像一个make this:

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

个字符

lzfw57am

lzfw57am5#

看了一些已经给出的答案,他们似乎很接近,激励我在不使用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

sulc1iza

sulc1iza6#

这是更一般的,非常简单,并将工作90或900天到未来

function sundaysInFuture(numDays) {
    const dt = new Date();
    const sundays = [];
    for (let i = 0; i < numDays; i++) {
      const thisDay = new Date(
        dt.getFullYear(),
        dt.getMonth(),
        dt.getDate() + i
      );
      if (thisDay.getDay() === 0) {
        sundays.push({
          dayOfMonth: thisDay.getDate(),
          iso: thisDay.toISOString(),
        });
      }
    }
    console.log(sundays);
    return sundays;
  }

字符串

相关问题