We've updated the ServiceNow Community Code of Conduct, adding guidelines around AI usage, professionalism, and content violations. Read more

GlideSchedule isInSchedule not working

Ramonrdd3
Tera Expert

I'm using a client catalog script and and client callable script include to implement a requirement and avoid the selection of weekend days and holidays on a date time field on a catalog item.
I'm using the glideSchedule isInSchedule method but I'm getting a false when selecting a week day.

Here is the client script

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || !newValue) {
        return;
    }

    // Get today's date (without time)
    var today = new Date();
    today.setHours(0, 0, 0, 0);

    // Get the selected date
    var selectedDate = new Date(newValue);
    selectedDate.setHours(0, 0, 0, 0);

    // Calculate 3 days in milliseconds
    var threeDaysMs = 3 * 24 * 60 * 60 * 1000;

    // Minimum allowed date = today + 3 days
    var minAllowedDate = new Date(today.getTime() + threeDaysMs);

    // First validation: 3 days rule
    if (selectedDate < minAllowedDate) {
        g_form.clearValue('date_required');
        g_form.showFieldMsg(
            'date_required', 'Date required must be 3 days (or more) from the current date.', 'error');
        return;
    }

    // SECOND VALIDATION: business days (Mon–Fri + excluding holidays)
    var ga = new GlideAjax('DateBusinessValidator');
    ga.addParam('sysparm_name', 'validateAndMinDate');
    ga.addParam('sysparm_schedule', 'a4f73987db2e2340917fd7795e961951'); // sys id schedule
    ga.addParam('sysparm_business_days', 3);
    ga.addParam('sysparm_date', newValue);

    ga.getXMLAnswer(function(answer) {
        console.log("DEBUG → RAW ANSWER from Script Include:", answer);
        try {
            var res = JSON.parse(answer);
            console.log("DEBUG → Parsed response:", res);
            if (!res.isBusinessDay) {
                console.warn("DEBUG → FAIL: isBusinessDay = false");
                g_form.clearValue('date_required');
                g_form.showFieldMsg('date_required', 'Selected date must be a business day (Mon–Fri, excluding holidays).', 'error');

            } else {
                console.log("DEBUG → PASS: isBusinessDay = true");
            }
        } catch (e) {
            console.error("DEBUG → JSON PARSE ERROR:", e);
            g_form.showFieldMsg('date_required', 'Error validating business day.', 'error');
        }
    });
}

Here is the Script include 

var DateBusinessValidator = Class.create();
DateBusinessValidator.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    validateAndMinDate: function() {

        // Read parameters
        var scheduleId = this.getParameter('sysparm_schedule');
        var minBusinessDays = parseInt(this.getParameter('sysparm_business_days'), 10);
        var dateStr = this.getParameter('sysparm_date');

        // DEBUG: incoming parameters
        gs.info("DEBUG SI → scheduleId: " + scheduleId);
        gs.info("DEBUG SI → minBusinessDays: " + minBusinessDays);
        gs.info("DEBUG SI → dateStr (raw): " + dateStr);

        // Load schedule
        var schedule = new GlideSchedule(scheduleId);
        gs.info("DEBUG SI → schedule loaded? " + (schedule ? "YES" : "NO"));

        // Force selected date to 09:00:00 to avoid timezone shifting
        var selected = new GlideDateTime(dateStr + " 09:00:00");
        gs.info("DEBUG SI → selected (with forced time): " + selected.getDisplayValue());
        gs.info("DEBUG SI → selected (internal): " + selected.getValue());

        // Check if selected date is a business day
        var isBusiness = schedule.isInSchedule(selected);
        gs.info("DEBUG SI → isBusinessDay: " + isBusiness);

        // Calculate minimum allowed business date
        var now = new GlideDateTime();
        now.setDisplayValue(now.getLocalDate().toString() + " 09:00:00");

        gs.info("DEBUG SI → now (forced 09:00): " + now.getDisplayValue());

        var minDate = new GlideDateTime(now);

        // Add business time: X days * 24h * 60m * 60s * 1000ms
        var ms = minBusinessDays * 24 * 60 * 60 * 1000;
        schedule.add(minDate, ms);

        gs.info("DEBUG SI → minBusinessDate (calculated): " + minDate.getDisplayValue());
        gs.info("DEBUG SI → minBusinessDate (local only): " + minDate.getLocalDate().toString());

        // Build response
        var result = {
            isBusinessDay: isBusiness,
            minBusinessDate: minDate.getLocalDate().toString()
        };

        gs.info("DEBUG SI → JSON returned: " + JSON.stringify(result));

        return JSON.stringify(result);
    }
});


here is my Schedule of 8 to 5 weekdays excluding holidays

Ramonrdd3_0-1770763535992.png

Scheduled entry

Ramonrdd3_1-1770763584951.png

I believe it could be because the "When" and "To" dates are in the past, however the schedule is set to repeat every weekday repeat until is empty.
Why I'm getting a false returned when selecting a week day in this case ?

2 ACCEPTED SOLUTIONS

Ankur Bawiskar
Tera Patron

@Ramonrdd3 
once you fix that schedule entry part highlighted by me below, check this link where it has solution

Business days Issue -> response from Dave_p

AnkurBawiskar_1-1770782598178.png

 

AnkurBawiskar_2-1770782610147.png

 

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

View solution in original post

 

Did you get it working? You can also just use an ui policy to handle the client side date restriction. 

lauri457_0-1770850634958.png

Also it might be simpler to make an all day workday schedule instead if you don't care about the working hours. And also make it floating tz so it uses the session timezone. Or you can set timezone on the gdts

 

Working with times is extremely difficult in my opinion but this is what I would do if i understand your requirement correctly, although i would probably have the n days in future restriction only on the client side

 

var date = new GlideDateTime(),
	now = new GlideDateTime(),
	schedule = new GlideSchedule("6bfda72083437210557ff0d6feaad315"),
	daysFromNow = 3,
	inputDate = "2026-02-15",
	result = {
		isDaysFromNow: false,
		isBusinessDay: false,
		minBusinessDate: ""
	};
//set times at midnight session tz
now.setDisplayValue(now.getDate())
date.setDisplayValue(inputDate + " 00:00:00");

//is date x bizdays from now
now.addDays(daysFromNow);
result.isDaysFromNow = GlideDateTime.subtract(date, now).getNumericValue() <= 0;

//is in schedule aka business day
result.isBusinessDay = schedule.isInSchedule(date);

//find start of next business day 00:00:00 in session time
var untilNext = schedule.whenNext(date) / 1000;
date.addSeconds(untilNext);
result.minBusinessDate = date.getLocalDate();

gs.info(JSON.stringify(result, null, 2));

/*
*** Script: {
  "isDaysFromNow": true,
  "isBusinessDay": false,
  "minBusinessDate": "2026-02-16"
}
*/

 

 

 

View solution in original post

11 REPLIES 11

Ankur Bawiskar
Tera Patron

@Ramonrdd3 

seems your schedule entry has wrong date 7th Dec 2018 is Friday

You should set that with Monday 3rd Dec 2008

 

AnkurBawiskar_0-1770781085739.png

 

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

Ankur Bawiskar
Tera Patron

@Ramonrdd3 
once you fix that schedule entry part highlighted by me below, check this link where it has solution

Business days Issue -> response from Dave_p

AnkurBawiskar_1-1770782598178.png

 

AnkurBawiskar_2-1770782610147.png

 

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

Hi @Ankur Bawiskar 
Thanks for your help.
I'm trying to adapt the code to my scenario.
But i don't see how with the provided solution, the code will prevent the selection of weekend days and holidays.
I can see on the last lines of the script include

var finalTime = schedule.add(nowDateTime, dur, '');
var updatedGdt = new GlideDateTime(dateSelected);
var finalTimeGdt = new GlideDateTime(finalTime);
if (updatedGdt < finalTimeGdt) {
     return 'true';
}
return 'false';


It's just checking if the selected date is within the range, in Paul's case, 15 business days.
There is nothing in place to check for weekend days or holidays, right ?

Hello @Ankur Bawiskar 

I have analyzed the provided solution and use it on my script include. However is not working as expected.
Here is the script include I'm currently using

var DateBusinessValidator = Class.create();
DateBusinessValidator.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    validateAndMinDate: function() {

        try {
            var response = 'false';
            var dateSelected = this.getParameter('sysparm_date');
			gs.info("DEBUG SI → dateSelected: " + dateSelected);

            var nowDateTime = new GlideDateTime();
			gs.info("DEBUG SI → nowDateTime " + nowDateTime.getValue());

            var days = 3;
            var duration = new GlideDuration(days * 24 * 60 * 60 * 1000);
			gs.info("DEBUG SI → duration is " + duration.getDisplayValue());

            var schedule = new GlideSchedule('a4f73987db2e2340917fd7795e961951', 'PST'); //8-5 weekdays excluding holidays

            var finalTime = schedule.add(nowDateTime, duration);
			gs.info("DEBUG SI → finalTime is " + finalTime);

            var updatedGdt = new GlideDateTime(dateSelected);
			gs.info("DEBUG SI → updateGdt is " + updatedGdt.getValue());

            var finalTimeGdt = new GlideDateTime(finalTime);
			gs.info("DEBUG SI → finalTimeGdt is " + finalTime.getValue());
			
            if (updatedGdt < finalTimeGdt) {
                response = 'true';
            }


            gs.info("DEBUG SI → JSON returned: " + JSON.stringify(response));

            return JSON.stringify(response);


        } catch (e) {
            gs.info("DEBUG SI → Error on Script Include: " + e);
        }



    },

    type: 'DateBusinessValidator'
});

Here is the onChange catalog client script

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || !newValue) {
        return;
    }
    
    var ga = new GlideAjax('DateBusinessValidator');
    ga.addParam('sysparm_name', 'validateAndMinDate');
    ga.addParam('sysparm_date', newValue);

    ga.getXMLAnswer(function(answer) {
        console.log("DEBUG → RAW ANSWER from Script Include:", answer);
        try {
            var res = JSON.parse(answer);
            console.log("DEBUG → Parsed response:", res);
            if (res == 'true') {
                console.warn("DEBUG → FAIL: Selected date is not after 3 days or a business day");
                g_form.clearValue('date_required');
                //g_form.showFieldMsg('date_required', 'Selected date must be a business day (Mon–Fri, excluding holidays).', 'error');
                g_form.showFieldMsg(
                    'date_required', 'Date required must be 3 days (or more) from the current date.', 'error');

            } else {
                console.log("DEBUG → PASS: Selected date is not within next 3 business days");
            }
        } catch (e) {
            console.error("DEBUG → JSON PARSE ERROR:", e);
            g_form.showFieldMsg('date_required', 'Error validating business day.', 'error');
        }
    });
}


And here are the logs of the script include

Ramonrdd3_0-1770846357870.png

I have added the order numbers so it's easier to read 😅
I have change also my schedule as you suggested

Ramonrdd3_1-1770846534154.png

But is not working, and i have a couple of questions.
First one, how is it that when i use the schedule.add() method, system returns a date about 9 business days from today. You can see it on the 4th log, it's showing 24th of february. That makes no sense. And i have logged the duration to make sure the calculation is fine, and it is, it's a 3 day duration as i need it.

Second question. I don't see how this code evaluates for weekend days, like saturdays or sundays, nor holidays.
It's just loading the schedule and adding a duration to it, but that's it.

@Ramonrdd3 

I have shared a link where it has working solution.

please check that and debug

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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