2009-10-30 24 views
11

は、どのように私は別の日付オブジェクトからヶ月未満のnは数です日付オブジェクトを作成することができますか?私はDateAdd()のようなものを探しています。別の日付オブジェクトから(6ヶ月前)日付オブジェクトを取得します

例:今すぐobjCurrentDateを使用して

var objCurrentDate = new Date(); 

、どのように私は今日の日付/ objCurrentDateより半年古い日付を持つ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); 
関連する問題