Reputation: 998
I just want to add 45 months to the given date in JavaScript. I have tried this:
var startDateFormat = new Date(2018, 11, 24); // 11 is for January starts from 0
var addDate = startDateFormat.setMonth(startDateFormat.getMonth() + 45); //want to add 45 months
console.log(new Date(addDate).getFullYear() + "-" + new Date(addDate).getMonth() + 1 + "-" + new Date(addDate).getUTCDate())
But the result is 2019-101-23. Can anybody help me why this is happening?
Upvotes: 1
Views: 5423
Reputation: 2663
45 months, means 3 years + 9 months. so use javascript divider and modulus operators something like this..
var startDateFormat = new Date(2018, 11, 24); // 11 is for January starts from 0
var year = startDateFormat.setYear(startDateFormat.getFullYear() + (45 / 12));
if ((startDateFormat.getMonth() + 1 + (45 % 12)) > 12)
{
year = new Date(year).setYear(new Date(year).getFullYear() + 1);
var month = startDateFormat.setMonth(startDateFormat.getMonth() + (45 % 12) - 12 + 1);
}
else
{
var month = startDateFormat.setMonth(startDateFormat.getMonth() + (45 % 12) + 1);
}
console.log(new Date(year).getFullYear() + "-" + new Date(month).getMonth() + "-" + new Date(month).getDate())
Thanks
Upvotes: 0
Reputation: 2078
Looking at your code, it seems like you need to play with dates a lot in your project. In that case, I suggest you to try momentjs library which makes playing with dates really easy.
e.g
moment([2010, 0, 31]); // January 31
moment([2010, 0, 31]).add(1, 'months'); // February 28
similarly, it had tons easy to use features. for more refer, http://momentjs.com/ and for documentation on the same visit http://momentjs.com/docs/
Upvotes: -2
Reputation: 1917
You should place new Date(addDate).getMonth() + 1
in parentheses. You are building a string and since you don't provide explicit precedence, first new Date(addDate).getMonth() gets added, then 1 gets concatenated to the string.
Try this:
var startDateFormat = new Date(2018, 11, 24);
var addDate = startDateFormat.setMonth(startDateFormat.getMonth() + 45);
console.log(new Date(addDate).getFullYear() + "-" + (new Date(addDate).getMonth() + 1) + "-" + new Date(addDate).getUTCDate())
Or template string:
var startDateFormat = new Date(2018, 11, 24);
var addDate = startDateFormat.setMonth(startDateFormat.getMonth() + 45);
console.log(`${new Date(addDate).getFullYear()}-${new Date(addDate).getMonth() + 1}-${new Date(addDate).getUTCDate()}`);
Upvotes: 1
Reputation: 1075467
There are a few problems there:
setMonth
modifies the state of the instance you call it on, you don't usually use its return value.+ 1
you're doing after getMonth
is adding a "1"
to the string. If you want it numerically, group it with the getMonth
.So:
var dt = new Date(2018, 11, 24); // 11 is for January starts from 0
dt.setMonth(dt.getMonth() + 45); //want to add 45 months
console.log(dt.getFullYear() + "-" + (dt.getMonth() + 1) + "-" + dt.getDate());
// Note parens ----------------------^-----------------^
Upvotes: 3