JavaScript function to add X months to a date

后端 未结 19 2093
星月不相逢
星月不相逢 2020-11-22 02:44

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.<

19条回答
  •  醉酒成梦
    2020-11-22 03:09

    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):

    Calculate Expiry Date
    
    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 [Date] // Note: Must contain a value to replace eg. [Date]
    document.getElementById("memexp").firstChild.data = calcval;
    
    // Stores the new date in a  for submission to database table
    document.getElementById("membershipsexpiry_date").value = calcval;
    }
    

提交回复
热议问题