catalog client script to calculate the date from the current date

Deepa12
Tera Contributor

HI, please assist me to create script to calculate 5 working days from the current date.

 

i want to show the error message if the date exceeded the 5 business working days.

3 REPLIES 3

Vasuki
Tera Contributor

Hi Deepa,

 

I am also a beginner in coding. I have tried the below one. Please try the below code. It might help you.

 

Please mark it helpful if it is helping you

function onLoad() {
    var currentDate = new GlideDateTime(); // Get current date and time
    var workingDaysToAdd = 5; // Number of working days to add
    var workingDaysCount = 0;
    var targetDate = new GlideDateTime(currentDate);

    while (workingDaysCount < workingDaysToAdd) {
        // Check if the current targetDate is a working day (Monday to Friday)
        if (targetDate.getDayOfWeek() != 1 && targetDate.getDayOfWeek() != 7) {
            workingDaysCount++;
        }
        targetDate.addDays(1); // Move to the next day
    }

    // Check if the calculated targetDate exceeds the 5 working days limit
    if (targetDate.compareTo(currentDate) > 0) {
        g_form.addErrorMessage("Error: Exceeded 5 working days limit");
    }

    // Display the calculated targetDate in a field on the form
    g_form.setValue("target_date_field", targetDate.getDisplayValue()); // Replace "target_date_field" with the actual field name
}

 

Ankur Bawiskar
Tera Patron
Tera Patron

@Deepa12 

check this link and it has solution. please enhance it as per your requirement

Select only Business Days excluding holidays 

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

SwarnadeepNandy
Mega Sage

Hi Deepa,

 

Please use the following in the catalog client script.

// Get the current date and time
var today = new GlideDateTime();
console.log("Today: " + today);

// Get the schedule by name
var schedule = new GlideSchedule("8-5 weekdays excluding holidays");

// Calculate 5 business working days from today using the schedule
var future = schedule.add(today, 5, "day");
console.log("Future: " + future);

// Get the variable by name
var future_date = g_form.getControl("future_date");

// Set the value of the variable to the future date
future_date.value = future.getDisplayValue();

// Use this to display error message based on your desired condition
g_form.addErrorMessage("The date is past 5 days");

 

Please modify the script accordingly as per your need.

 

Kind Regards,

Swarnadeep Nandy