How to add months by quarter using JavaScript
Hereby i am the following inputs:
Months to be separated by : 4 months
Will have the date with month and year: 07-05-2011.
Now i need to add months by 4 using JavaScript or jquery. How can this be done?
For example:
I am having the date as : 01-01-2011 and the duration is 4
My output should be:
01-12-2010
01-04-2011
01-08-2011
01-12-2011
For开发者_高级运维 example if it is:
I am having the date as : 01-06-2011 and the duration is 4
My output should be:
01-06-2011
01-10-2011
01-02-2012
01-06-2012
Thanks in advance
Here you have:
var initialDate = new Date(2011, 5, 1); //Your example number two. January is 0
for(var i=0; i<4; i++){
var newMonth = initialDate.getMonth() + i;
var newYear = initialDate.getYear();
if(newMonth >= 12){
newMonth = newMonth % 12;
newYear ++;
}
var newDate = new Date(newYear, newMonth, 1);
alert(newDate);
}
Hope this helps. Cheers
A Date object has a getMonth method and setMonth method which takes an integer (the number of months).
So maybe a function:
function GetNextPeriod(basisDate){
// Copy the date into a new object
var basisDate = new Date(basisDate);
// get the next month/year
var month = basisDate.getMonth() +4;
var year = basisDate.getFullYear();
if (month >= 12){
month -= 12;
year++;
}
// set on object
basisDate.setMonth(month);
basisDate.setFullYear(year);
// return
return basisDate;
}
var period1 = GetNextPeriod(inputDate);
var period2 = GetNextPeriod(period1);
var period3 = GetNextPeriod(period2);
There is nothing built into the native Date object to do any date arithmetic like this. You can either settle for writing your own function to add the number of milliseconds in 4 months, or you could check out DateJS.
Here's a function that takes a string like 01-06-2011
, turns it into a date variable, adds four months, and returns the result as a string in the same dd-mm-yyyy format:
function addFourMonths(dateString) {
var dateParts = dateString.split('-');
var newDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
newDate.setMonth(newDate.getMonth() + 4);
return newDate.getDate() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getFullYear();
}
To use:
var myDate = addFourMonths('01-12-2011');
alert('The date is ' + myDate);
Result (live demo):
'The date is 1-4-2012.'
Note that the year is incremented automatically when using setMonth(newmonth)
if newmonth
is greater than 12, so there's no need to test for that as some of the other answers presented here do.
From the MDC docs for setMonth:
"If a parameter you specify is outside of the expected range, setMonth attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1 (year + 1), and 3 will be used for month."
精彩评论