2009-10-30 243 views
11

如何創建一個日期對象小於ň個月的數量從另一個約會對象?我正在尋找類似DateAdd()的東西。獲取Date對象(半年前),從另一個日期對象

例子:

var objCurrentDate = new Date(); 

現在使用objCurrentDate,我怎麼能產生具有日期比今天的日期/ objCurrentDate大6個月Date對象?

回答

27

您可以實現非常容易的「addMonths」功能:

function addMonths(date, months) { 
    date.setMonth(date.getMonth() + months); 
    return date; 
} 


addMonths(new Date(), -6); // six months before now 
// Thu Apr 30 2009 01:22:46 GMT-0600 

addMonths(new Date(), -12); // a year before now 
// Thu Oct 30 2008 01:20:22 GMT-0600 
1
var oldDate:Date = new Date(); 
/* 
Check and adjust the date - 
At the least, make sure that the getDate() returns a 
valid date for the calculated month and year. 
If it's not valid, change the date as per your needs. 
You might want to reset it to 1st day of the month/last day of the month 
or change the month and set it to 1st day of next month or whatever. 
*/ 
if(oldDate.getMonth() < n) 
    oldDate.setFullYear(oldDate.getFullYear() - 1); 
oldDate.setMonth((oldDate.getMonth() + n) % 12); 
0

創建Date對象,並通過n的值,其中n是月數(加/減)。

var dateObj = new Date(); 
    var requiredDate= dateObj.setMonth(dateObj.getMonth() - n);