getting number of working days between start date and end date

akhil_kusa
ServiceNow Employee
ServiceNow Employee

I'm new to learning ServiceNow, and I'm developing a mock PTO (Paid Time Off) application. I'm encountering difficulties in calculating the business days between two dates and checking for insufficient PTO balance. Below are my client script and script includes. Could you please review them and provide corrections?

ClientScript :

 

 

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

    var start = g_form.getValue('start_date');
    var balance = parseFloat(g_form.getValue('balance'));


    //Type appropriate comment here, and begin script below
    var ga = new GlideAjax('PTOAjax');
    ga.addParam('sysparm_name', 'getDatediff');
    ga.addParam('sysparm_start', start);
    ga.addParam('sysparm_end', newValue);

    ga.getXML(getDuration);


    function getDuration(response, balance) {
        var answer = response.responseXML.documentElement.getAttribute("answer");
        var days = (answer / (1000 * 60 * 60 * 24)) + 1;

        if (answer > balance) {
            g_form.addErrorMessage("Insufficient PTO");
            g_form.clearValue('duration');
            g_form.clearValue('end_date');

        } else {
            g_form.clearMessages();
            g_form.setValue('duration', days);
        }
    }

 

 

 

Script Include:

 

 

    getDatediff: function() {
        var startDate = new GlideDateTime();
        startDate.setDisplayValue(this.getParameter('sysparm_start'));
        var endDate = new GlideDateTime();
        endDate.setDisplayValue(this.getParameter('sysparm_end'));

        var schedule = new GlideSchedule('2d37aaa69781c2102z0036e71153afd9', gs.getProperty('glide.sys.default.tz'));

        var duration1 = schedule.duration(startDate, endDate);
        return duration1.getNumericValue();

    },

type: 'PTOAjax'

 

 

 

Appreciate your quick help!

 

@Ankur Bawiskar 

11 REPLIES 11

akhil_kusa
ServiceNow Employee
ServiceNow Employee

@Deepak Shaerma below is my req

To calculate duration between the start date and end date, considering only business days (weekdays) and based on the provided schedule, if exceeds the PTO balance: An error message will be displayed stating "Insufficient PTO". The duration and end date fields will be cleared. If the calculated duration falls within the PTO balance: The duration field will be set with the estimated number of business days. No error messages will be displayed.

 

Thanks for the help

@akhil_kusa 

1. Calculate Business Days (Client-Side Script)

For calculating the number of business days between two dates, you can write a client script that triggers on change of either the “Start Date” or “End Date” fields.

function calculateBusinessDays(startDate, endDate) {
    var start = new Date(startDate);
    var end = new Date(endDate);
    var count = 0;
    
    while (start <= end) {
        var dayOfWeek = start.getDay();
        if(dayOfWeek != 0 && dayOfWeek != 6) count++; // 0=Sunday, 6=Saturday
        start.setDate(start.getDate() + 1); // Increase day by 1
    }
    
    return count;
}

2. Checking PTO Balance (Server-Side Script)

For checking PTO balance and displaying an error message if the duration exceeds the available PTO, you might need a GlideAjax call from the client script to the server to validate the PTO balance:

function checkPTOBalance(duration) {
    var ga = new GlideAjax('PTOAjaxProcessor');
    ga.addParam('sysparm_name', 'checkBalance');
    ga.addParam('sysparm_duration', duration);
    ga.getXMLAnswer(function(response) {
        var result = response;
        if (result == 'insufficient') {
            // Show error message, clear duration and end date fields
            g_form.clearValue('duration');
            g_form.clearValue('end_date');
            g_form.showErrorBox('duration', 'Insufficient PTO');
        } else {
            // Set the duration field with estimated number of business days
            g_form.setValue('duration', duration);
        }
    });
}

Server-Side Part (Script Include named PTOAjaxProcessor):

var PTOAjaxProcessor = Class.create();
PTOAjaxProcessor.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    checkBalance: function() {
        var duration = this.getParameter('sysparm_duration');
        // Assume getPOTBalance is a function that retrieves the user’s PTO balance
        var ptoBalance = this.getPTOBalance();

        if (ptoBalance < duration) {
            return 'insufficient'; // If PTO balance is insufficient
        }
        return 'sufficient'; // If PTO balance is enough
    },

    getPTOBalance: function() {
        // Write actual logic here to retrieve the user’s current PTO balance
        return 10; // Placeholder return value
    },

    type: 'PTOAjaxProcessor'
});


Meanwhile Please Mark my responses given Helpful and Accepted Solution. If this Helps you to understand. This will help us a lot.
- Keep Learning ‌‌
Thanks & Regards 
Deepak Sharma