Reputation: 11656
I am trying to add months to a date based on month variable, but I get wrong result when I try to fetch month from an input field and pass it. and I get the correct result if I myself define a variable and pass it to setMonth.
here is the code :
when I use static value :
.on('changeDate', function(e){
var datea = new Date(e.date);
console.log(datea);
// var montha = $('#duration').val();
// console.log(montha);
montha = 3 ;
datea.setMonth(datea.getMonth()+ montha);
datea = datea.getDate() + "/" + datea.getMonth() + "/" + datea.getFullYear();
console.log(datea);
$('#end_date').val(datea);
});
console output :
Sat Apr 01 2017 00:00:00 GMT+0530 (India Standard Time)
1/6/2017
as you can see it prints correct output
but If I try fetching the month value from an input field
.on('changeDate', function(e){
var datea = new Date(e.date);
console.log(datea);
var montha = $('#duration').val();
console.log(montha);
datea.setMonth(datea.getMonth()+ montha);
datea = datea.getDate() + "/" + datea.getMonth() + "/" + datea.getFullYear();
console.log(datea);
$('#end_date').val(datea);
});
Console output :
Sat Apr 01 2017 00:00:00 GMT+0530 (India Standard Time)
3
1/9/2019
even though the montha has value 3 the output result is not correct.
Please help me solve this
Upvotes: 0
Views: 67
Reputation: 372
I took a check in my browser console, and I think the issue may cause by the input value was not casting to number type. From the below picture, the date1 is adding 3 (number type) to setMonth function, then get the correct date "2017/7/...". However, the date2 is adding '3'(string type) to setMonth function then get date "2019/10/...".
Upvotes: 2