Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to add 10 days to current date using client scripts

anur
Kilo Contributor

I have a field "RequestedDate" in a service catalog form. Need to populate it with value equal to current date plus 10 days.

Please suggest implementing this with a client script.

7 REPLIES 7

You can do it by setting the default value of the variable. You can check the below blog



Auto-populating and validating date fields



Please mark this response as correct or helpful if it assisted you with your question.

Sriramachandra
Tera Guru

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}

// Get start date from field
var startDateStr = g_form.getValue('u_start_date');
var startDate = new Date(startDateStr);

// Add 5 days
startDate.setDate(startDate.getDate() + 5);

// Format to user's date format or standard YYYY-MM-DD
var yyyy = startDate.getFullYear();
var mm = String(startDate.getMonth() + 1).padStart(2, '0');
var dd = String(startDate.getDate()).padStart(2, '0');

var formattedEndDate = yyyy + '-' + mm + '-' + dd;

// Set the value in 'u_end_date' field
g_form.setValue('u_end_date', formattedEndDate);
}

Sriramachandra
Tera Guru

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') return;

var startDateStr = g_form.getValue('u_start_date');
var endDateStr = g_form.getValue('u_end_date');

if (!startDateStr || !endDateStr) return;

var startDate = new Date(startDateStr);
var endDate = new Date(endDateStr);

var diffTime = endDate - startDate;
var diffDays = diffTime / (1000 * 60 * 60 * 24);

if (diffDays < 0) {
g_form.showFieldMsg('u_end_date', 'End date cannot be before start date.', 'error');
g_form.setValue('u_end_date', '');
} else if (diffDays > 365) {
g_form.showFieldMsg('u_end_date', 'End date cannot be more than 365 days from start date.', 'error');
g_form.setValue('u_end_date', '');
}
}