2009-06-22 111 views
19

有誰知道我怎樣才能在此基礎上本週日,下週日期?舉例來說,如果我有這個週四日期(25/6/2009)我如何使用JavaScript來獲取下週四日(2009/2/7)?如何獲得下週日期在JavaScript

回答

42
var firstDay = new Date("2009/06/25"); 
var nextWeek = new Date(firstDay.getTime() + 7 * 24 * 60 * 60 * 1000); 

你也可以看看DateJS如果你喜歡 「流利」 的API。

9
Date.prototype.addDays = function (d) { 
    if (d) { 
     var t = this.getTime(); 
     t = t + (d * 86400000); 
     this.setTime(t); 
    } 
}; 

this_week.addDays(7); 
+0

我喜歡它...! +1 – Cerebrus 2009-06-22 06:29:46

+1

雖然我會讓日期原型獨立。 – glmxndr 2009-06-22 06:30:46

+1

爲什麼單獨放置日期原型? – razzed 2009-06-22 06:35:18

28
function nextweek(){ 
    var today = new Date(); 
    var nextweek = new Date(today.getFullYear(), today.getMonth(), today.getDate()+7); 
    return nextweek; 
} 
8

函數dateObject.getNextWeekDay返回對象自己的日期後的下一個工作日。

Date.prototype.getNextWeekDay = function(d) { 
 
    if (d) { 
 
    var next = this; 
 
    next.setDate(this.getDate() - this.getDay() + 7 + d); 
 
    return next; 
 
    } 
 
} 
 

 
var now = new Date(); 
 
var nextMonday = now.getNextWeekDay(1); // 0 = Sunday, 1 = Monday, ... 
 
var secondNextMonday = new Date(nextMonday).getNextWeekDay(1); 
 
console.log('Next Monday : ' + nextMonday); 
 
console.log('Second Next Monday : ' + secondNextMonday);

1

函數返回下一weekdaay:

function getNextWeekDay (startDate, dayOfWeek){ 
    var dayOffset = dayOfWeek > startDate.getDay() 
     ? dayOfWeek - startDate.getDay() 
     : dayOfWeek - startDate.getDay() + 7; 

    startDate.setDate(startDate.getDate() + dayOffset); 

    return startDate; 
} 

var now = new Date(); 

var nextMonday = getNextWeekDay(new Date(),1); // 0 = Sunday, 1 = Monday, ... 
var nextSaturday = getNextWeekDay(new Date(),6); 
var nextSunday = getNextWeekDay(new Date(),0); 
var secondNextMonday = getNextWeekDay(new Date(now.getTime() + (7 *24 * 60 * 60 * 1000)),1); 
alert(nextMonday+ '- '+nextSaturday+ '- '+nextSunday+ '- '+secondNextMonday); 
相關問題