how can i find number of days between two dates excluding weekends

mishra007
Tera Contributor

how can i find number of days between two dates excluding weekends

3 REPLIES 3

Dr Atul G- LNG
Tera Patron
Tera Patron

Hi @mishra007 

 

https://www.servicenow.com/community/developer-forum/how-to-calculate-datediff-in-days-excluding-wee...

 

*************************************************************************************************************
If my response proves useful, please indicate its helpfulness by selecting " Accept as Solution" and " Helpful." This action benefits both the community and me.

Regards
Dr. Atul G. - Learn N Grow Together
ServiceNow Techno - Functional Trainer
LinkedIn: https://www.linkedin.com/in/dratulgrover
YouTube: https://www.youtube.com/@LearnNGrowTogetherwithAtulG
Topmate: https://topmate.io/atul_grover_lng [ Connect for 1-1 Session]

****************************************************************************************************************

swathisarang98
Giga Sage
Giga Sage

Hi @mishra007 ,

 

Please refer to below article,

https://www.servicenow.com/community/developer-forum/getting-number-of-working-days-between-start-da... 

 

Please mark this comment as Correct Answer/Helpful if it helped you.

Regards,

Swathi Sarang

Gustav Aldenbra
Kilo Sage

hi @mishra007 

 

You could use below script to do this. The code is server side so if you want present the days between when setting the values in the client you can modify the script a bit and use it in a script include and call it using GlideAjax

 

function daysBetween(startDate, endDate) {
    // Parse the start and end dates
    var start = new GlideDateTime(startDate);
    var end = new GlideDateTime(endDate);

    var count = 0; // This will count the number of days excluding weekends
    var currentDate = start;

    // Loop from the start date to the end date
    while (currentDate.getNumericValue() <= end.getNumericValue()) {
        var dayOfWeek = currentDate.getDayOfWeek();
        
        if (dayOfWeek != 6 && dayOfWeek != 7) { // Skip weekends
            count++;
        }
        // Move to the next day
        currentDate.addDays(1);
    }

    // Subtract one day because the start day is included in the count
    return count - 1;
}

// Example
var startDate = '2024-02-23';
var endDate = '2024-02-27';
var workingDays = daysBetween(startDate, endDate);
gs.info("Working days: " + workingDays);