Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

date difference without weekends using moment js

// npm i moment --save
// npm i moment-business-days --save

var moment = require('moment');
var moment_business_days = require('moment-business-days');

//use this if it works for you
//var date_count = moment_business_days('2022-06-20', 'MM-DD-YYYY').businessDiff(moment_business_days('2022-07-08','MM-DD-YYYY'));

function countDateRange(start_date, end_date, included_days = [0, 1, 2, 3, 4, 5, 6]){ // 0 as Sunday - 6 as Saturday
    //set working days
  	moment_business_days.updateLocale('us', {
    	workingWeekdays: included_days
    });
	
  	//get difference between dates
    var date_diff = moment(end_date).diff(moment(start_date), 'days')
    var result = 0
    var date = start_date
	
    //check first day
    if(moment_business_days(date, 'YYYY-MM-DD').isBusinessDay()){
    	result += 1
    }
    
  	//check all days
    for (let i = 1; i <= date_diff; i++) {
        date = moment(date).add(1, 'days').format("YYYY-MM-DD")

        if(moment_business_days(date, 'YYYY-MM-DD').isBusinessDay()){
          	result += 1
        }
    }

    return result
}

var date_count = countDateRange('2022-06-20', '2022-07-08', [1, 2, 3, 4, 5])
console.log(date_count)
Source by momentjscom.readthedocs.io #
 
PREVIOUS NEXT
Tagged: #date #difference #weekends #moment #js
ADD COMMENT
Topic
Name
6+4 =