date format getting changed in onchange in client script

Simona6
Tera Contributor

Two fields on form start date and end date.Expecting as we fill start date(date), end date(date) will be automatically populate date of next two days. 

Executing Onchange Client script calling script include but the date format for end date is not same as start date.

e.g if start date is 11/10/2023 then end date is 11-12-2023

 

Any solution.

1 ACCEPTED SOLUTION

@Simona6 

use this onchange client script on start date

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading) {
		return;
	}
	var dateMS = getDateFromFormat(newValue, g_user_date_format);
	dateMS += 2 * 24 * 60 * 60 * 1000; // 2 here indicates days count
	var newDT = new Date();
	newDT.setTime(dateMS);
	g_form.setValue('u_review_end_date',formatDate(newDT, g_user_date_format));
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

9 REPLIES 9

@Simona6 

you simply want to add 2 days to start date and set in end date right?

if yes then no script include is required for this

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@Ankur Bawiskar yes as i will change the start date, end date need to be populated with 2days next to start date.

 

Simona6
Tera Contributor

@Ankur Bawiskar can you please share how to proceed without using script include and without getting any error in date format.

@Simona6 

use this onchange client script on start date

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading) {
		return;
	}
	var dateMS = getDateFromFormat(newValue, g_user_date_format);
	dateMS += 2 * 24 * 60 * 60 * 1000; // 2 here indicates days count
	var newDT = new Date();
	newDT.setTime(dateMS);
	g_form.setValue('u_review_end_date',formatDate(newDT, g_user_date_format));
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Thank @Ankur Bawiskar 

solution works totally fine.

Can we use below approach also instead of using 

dateMS += 2 * 24 * 60 * 60 * 1000;

 

This also works fine from me:

var dateMS = new Date(getDateFromFormat(newValue, g_user_date_format));
dateMS.setDate(dateMS.getDate() + 2);//add 2 days
var newDT = formatDate(dateMS, g_user_date_format);
g_form.setValue('u_review_end_date',newDT);