2009-10-30 18 views
11

मैं एक तारीख वस्तु जो एक और तारीख वस्तु से कम से कम n महीनों की संख्या है कैसे बना सकते हैं से प्राप्त करें? मैं DateAdd() जैसे कुछ ढूंढ रहा हूं।एक तारीख वस्तु (छह माह पहले) एक और तारीख वस्तु

उदाहरण:

var objCurrentDate = new Date(); 

अब objCurrentDate का उपयोग कर, मैं कैसे एक तारीख है जो आज की तारीख/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

तारीख वस्तु बना सकते हैं और n के मूल्य पारित, जहां n संख्या (जोड़ने/उप) महीने का है।

var dateObj = new Date(); 
    var requiredDate= dateObj.setMonth(dateObj.getMonth() - n); 
संबंधित मुद्दे