用于显示周末日期的JavaScript应用程序?

时间:2017-01-07 20:12:57

标签: javascript jquery date weekend

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

如果现在是周末,请告诉它本周末的日期,如果没有,那就是下周末的日期。

我在等你的帮助。 方面。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我将“最近的”周末解释为周一和周二的上周末,以及周四和周五的下周末。您没有提供有关如何处理星期三的任何信息。

然而,从其他答案来看,您似乎想要在周六和周日的当前周末以及工作日的下周末。

以下内容比其他答案更简洁:

deli(X):-
    deli(X,1).
deli(X,X):-
    write(X),nl.
deli(X,N):-
    Z is X mod N,
    Z==0,
    write(N),nl,
    N1 is N+1,
    deli(X,N1).
deli(X,N):-
    N1 is N+1,
    deli(X,N1).