Page 1 of 1

How to add months to a date ?

Posted: Fri Dec 23, 2022 12:28 am
by yvesf
Hello,

I would like to add month to a date. I have got 2 dates in my edit form, the today's date and another date which should be 1 month after the date of the first chosen date. I know how to add days but I cannot find out how to add month.
I have tried that piece of code

Code: Select all

function AddMonthsToDateObject(i, months) {
 let 0 = $('#' + i);
let d = nuFORM.removeFormatting(o.val(), o.attr('data-nu-format'));
	nuSetDateValue(i ,new Date(d).addMonths(months));
}
It seems that addMonths() doesn't exist in Javascript. I have maybe to add months by using getMonth() and setMonth() but I haven't found yet. Anyone did that already ?
Many thanks

Yves

Re: How to add months to a date ?

Posted: Fri Dec 23, 2022 9:54 am
by kev1n

Re: How to add months to a date ?

Posted: Sat Dec 24, 2022 1:25 am
by yvesf

Code: Select all

function AddMonthsToDateObject(i, months) {
 let 0 = $('#' + i);
let d = nuFORM.removeFormatting(o.val(), o.attr('data-nu-format'));
	nuSetDateValue(i ,new Date(d).setMonth(d.getMonth() + months));
}
AddMonthsToDateObject('date_field_to_add_month',1);
This function doesn't work, I don't understand why. Any idea ?

Re: How to add months to a date ?

Posted: Sat Dec 24, 2022 1:50 am
by yvesf
It seems that getMonth() is not recognized as a Javascript function

Re: How to add months to a date ?

Posted: Sun Dec 25, 2022 2:04 am
by yvesf
I have found the solution !!

Code: Select all

function addMonthsToDateObject(i, months) {
	let o = $('#' + i);
	let d = nuFORM.removeFormatting(o.val(), o.attr('data-nu-format'));  // remove format
const date = new Date(d); // creation new date based on d
date.setMonth(date.getMonth() + months); // the calcul is working when it's not done in a nuSetDateValue() function

nuSetDateValue(i , date); // you put date in the right field
}

addMonthsToDateObject('date_field_to_add_month',1);