allogos allogos - 6 months ago 24
jQuery Question

jquery Add number of months to start date

I want to add X number of months to my selected date from date picker,and number of months from my dropdown, I'm using below code:

$('#start_date').change(function(){
var months = $('#month_number').val();
var end = new Date($(this).val());
end.setMonth(end.getMonth() + months);
$('#date_hid_m').val( (end.getMonth() + 1) + '/' + end.getDate() + '/' + end.getFullYear()) ;


But the result is incorrect. E.g: if my start date is: MAY 28, 2016 and i want to add 6 months, the result shows 11/28/2019 !!!

Answer

In your code months is a string, because its value is retrieved from an input text element. So its value will get concatenated to end.getMonth(), not added as a number. You're getting 56 (=5+'6') months instead of 11 (=5+6) months there.

Solve this by converting the string to a number with a +:

var months = +$('#month_number').val();