JavaScript function to add X months to a date

2018-12-31 14:36发布

I’m looking for the easiest, cleanest way to add X months to a JavaScript date.

I’d rather not handle the rolling over of the year or have to write my own function.

Is there something built in that can do this?

17条回答
忆尘夕之涩
2楼-- · 2018-12-31 14:54

I think this should do it:

var x = 12; //or whatever offset
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + x);

I believe it should automatically handle incrementing to the appropriate year and mod-ing to the appropriate month.

try it

查看更多
看淡一切
3楼-- · 2018-12-31 14:54
var a=new Date();
a.setDate(a.getDate()+5);

As above stated method, you can add month to Date function.

查看更多
泪湿衣
4楼-- · 2018-12-31 14:56

As most of the answers highlighted, we could use setMonth() method together with getMonth() method to add specific number of months to a given date.

Example: (as mentioned by @ChadD in his answer. )

var x = 12; //or whatever offset 
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + x);

But we should carefully use this solution as we will get trouble with edge cases.

To handle edge cases, answer which is given in following link is helpful.

https://stackoverflow.com/a/13633692/3668866

查看更多
爱死公子算了
5楼-- · 2018-12-31 14:58

Sometimes useful create date by one operator like in BIRT parameters

I made 1 month back with:

new Date(new Date().setMonth(new Date().getMonth()-1));   
查看更多
孤独寂梦人
6楼-- · 2018-12-31 15:00

Taken from @bmpsini and @Jazaret responses, but not extending prototypes: using plain functions (Why is extending native objects a bad practice?):

function isLeapYear(year) { 
    return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 
}

function getDaysInMonth(year, month) {
    return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}

function addMonths(date, value) {
    var d = new Date(date),
        n = date.getDate();
    d.setDate(1);
    d.setMonth(d.getMonth() + value);
    d.setDate(Math.min(n, getDaysInMonth(d.getFullYear(), d.getMonth())));
    return d;
}

Use it:

var nextMonth = addMonths(new Date(), 1);
查看更多
倾城一夜雪
7楼-- · 2018-12-31 15:04

The following is an example of how to calculate a future date based on date input (membershipssignup_date) + added months (membershipsmonths) via form fields.

The membershipsmonths field has a default value of 0

Trigger link (can be an onchange event attached to membership term field):

<a href="#" onclick="calculateMshipExp()"; return false;">Calculate Expiry Date</a>

function calculateMshipExp() {

var calcval = null;

var start_date = document.getElementById("membershipssignup_date").value;
var term = document.getElementById("membershipsmonths").value;  // Is text value

var set_start = start_date.split('/');  

var day = set_start[0];  
var month = (set_start[1] - 1);  // January is 0 so August (8th month) is 7
var year = set_start[2];
var datetime = new Date(year, month, day);
var newmonth = (month + parseInt(term));  // Must convert term to integer
var newdate = datetime.setMonth(newmonth);

newdate = new Date(newdate);
//alert(newdate);

day = newdate.getDate();
month = newdate.getMonth() + 1;
year = newdate.getFullYear();

// This is British date format. See below for US.
calcval = (((day <= 9) ? "0" + day : day) + "/" + ((month <= 9) ? "0" + month : month) + "/" + year);

// mm/dd/yyyy
calcval = (((month <= 9) ? "0" + month : month) + "/" + ((day <= 9) ? "0" + day : day) + "/" + year);

// Displays the new date in a <span id="memexp">[Date]</span> // Note: Must contain a value to replace eg. [Date]
document.getElementById("memexp").firstChild.data = calcval;

// Stores the new date in a <input type="hidden" id="membershipsexpiry_date" value="" name="membershipsexpiry_date"> for submission to database table
document.getElementById("membershipsexpiry_date").value = calcval;
}
查看更多
登录 后发表回答