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.

addDaysUTC() is not counting current day

Hari1
Mega Sage

Hi,

I have a requirement to count days excluding weekends. I have a date range for an example.

12/Jan/2022 - 25/Jan/2022, returns 9 days where as it return 10 days.

Below is the code that i am using

Client Script:

var fromDate = g_form.getValue("from_date");
var toDate = g_form.getValue("to_date");

var ajax = new GlideAjax('CalDiffDateIteration');
        ajax.addParam('sysparm_name', 'durCalc');
        ajax.addParam('sysparm_fromDate', fromDate);
        ajax.addParam('sysparm_toDate', toDate);
        ajax.getXML(returnIterationDays);

        function returnIterationDays(response) {
            var answer = response.responseXML.documentElement.getAttribute("answer");
            answer = parseInt(answer);
	    
            g_form.setValue(setItrNum, answer);
        }

Script Include:

var CalDiffDateIteration = Class.create();
CalDiffDateIteration.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
    durCalc: function() {
		
		var fromDate = new GlideDateTime(this.getParameter('sysparm_fromDate'));
        var toDate = new GlideDateTime(this.getParameter('sysparm_toDate'));

       

        var days = getDateDiffExcWeekends(fromDate, toDate);
		
		return days;
		
        function getDateDiffExcWeekends(start, end) {
			
			gs.info("Script - start:" + start);
			gs.info("Script - end:" + end);
			
            var days = 0;
            while (start < end) {
                start.addDaysUTC(1);

                if (start.getDayOfWeekUTC() != 6 && start.getDayOfWeekUTC() != 7) {
                    days++;
                }
            }
			
			gs.info("Script - days:" + days);
            return days;
        }
    }
});
1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

I used this and it gave me 10 days

var startDateGdt = new GlideDateTime('2022-01-12 00:00:00');

var endDateGdt = new GlideDateTime('2022-01-25 00:00:00');

var days = getDateDiffExcWeekends(startDateGdt,endDateGdt);

gs.info(days);

function getDateDiffExcWeekends(start,end){
        var days = 0;
        while (start < end) {
            start.addDaysUTC(1);
            if (start.getDayOfWeekUTC() != 6 && start.getDayOfWeekUTC() != 7){
                days++ ;
            }
        }
        return days+1;
}

Output:

find_real_file.png

Regards
Ankur

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

View solution in original post

5 REPLIES 5

Community Alums
Not applicable

Hi Hari,

 

Just return days+1 in your script. It will work fine.

 

Thanks,

Visakha