JavaScript申请显示周末日期?

JavaScript application for showing the weekend dates?

我想了很多-我试过了,但我无法解决。我需要一个 JavaScript 应用程序来显示当前日期中最近的周末日期。

如果现在是周末,则提供本周末的日期,如果不是,则提供下周末的日期。

我在等你的帮助。 尊重。

您可以使用内置的 Date 构造函数。

var date = new Date();
var day = date.getDay();
var saturday;
var sunday;
if(day === 0 || day === 6){ //0 for Sunday, 6 for Saturday
    saturday = date;
    sunday = new Date(saturday.getTime());
    sunday.setDate(saturday.getDate() + (day === 0 ? -1 : 1));
    if(day === 0){
        var temp = saturday;
        saturday = sunday; //Confusing, but they are actually the wrong dates, so we are switching the dates
        sunday = temp;
        temp = null; //Free up some memory!
    }
        
}
else{
    //This is the complicated part, we need to find when is the next Saturday
    saturday = new Date(date.getFullYear(), date.getMonth(), (date.getDate() + 6) - day);
    sunday = new Date(saturday.getTime());
    sunday.setDate(saturday.getDate() + (saturday.getDay() === 0 ? -1 : 1));
}
date = day = null; //Free up some memory!
document.body.innerText = [saturday, sunday];

要获取日期,请使用 saturday.getDate()sunday.getDate()。请记住,Date 月份是从 0 开始的。有关详细信息,请参阅 here

 var chosenDay = new Date();
    var box = [];
    var counting = 0;
    for (var i = 0; i < 7; i++) {
      chosenDay.setDate(chosenDay.getDate() + counting);
      var day = chosenDay.getDate();
      var dayy = chosenDay.getDay();
      var month = chosenDay.getMonth()+1;
      var year = chosenDay.getFullYear();
      box.push({day: day, dayy: dayy});
      counting = 1;
    };

现在查找周六和周日

box.map(function(obj) {
 if (obj.dayy === 6) {
  console.log('Saturday found');
  alert(obj.day);
}; 
 if (obj.dayy === 0) {
  console.log('Sunday found');
  alert(obj.day);
};
});

我将 "nearest" 周末解释为周一和周二的前一个周末,以及周四和周五的下一个周末。您没有提供有关如何处理星期三的任何信息。

但是,从其他答案来看,您似乎想要星期六和星期日的当前周末和/或工作日的下一个周末。

以下比其他答案简洁一点:

/* Get nearest weekend to the provided date
** @param {Date} date - date to get weekends nearst to
** @returns {Array} array of Dates [Saturday, Sunday]
*/
function getNearestWeekend(date) {
  // Copy date so don't mess with provided date
  var d = new Date(+date);
  // If weekday, move d to next Saturday else to current weekend Saturday
  if (d.getDay() % 6) {
    d.setDate(d.getDate() + 6 - d.getDay());
  } else {
    d.setDate(d.getDate() - (d.getDay()? 0 : 1));
  }
  // Return array with Dates for Saturday, Sunday
  return [new Date(d), new Date(d.setDate(d.getDate() + 1))]
}

// Some tests
[new Date(2017,0,7),  // Sat 7 Jan
 new Date(2017,0,8),  // Sun 8 Jan
 new Date(2017,0,9),  // Mon 9 Jan
 new Date(2017,0,12)  // Thu 12 Jan
].forEach(function(d) {
  var opts = {weekday:'short', day:'numeric', month:'short'};
  console.log('Date: ' + d.toLocaleString('en-GB',opts) + ' | Next weekend: ' +
              getNearestWeekend(d).map(d =>d.toLocaleString('en-GB',opts)).join(' and ')
  );
});