srikarg
srikarg

Reputation: 331

Get Elapsed Weekdays Between Two Dates Using MomentJS

Is there any way to get the elapsed work days between two dates with MomentJS? The work days would be the week without the weekend, or Monday, Tuesday, Wednesday, Thursday, and Friday. So far, I tried using the diff() method (http://momentjs.com/docs/#/displaying/difference/) as follows:

var daysElapsed = today.diff(past, 'days');

As far as I know, the diff() only works by providing all the days between two dates, including weekend days. Thanks for your time!

Upvotes: 1

Views: 6403

Answers (3)

Renan Souza
Renan Souza

Reputation: 915

Although this question is pretty old, I've stumbled against it and couldn't find really an answer for what I was looking for.

I hope this solution might be helpful for other people too:

const momentStart = moment(initialDate);
const momentFinal = moment(finalDate);

// Get the diff in days between both dates
const diff = momentFinal.diff(momentStart, "days");

// If diff is 7 or bigger, all days are included
if (diff >= 7) {
  return moment.weekdays();
}

// Need to calculate, check which day we start from
const firstDay = momentStart.day();
const weekdaysBetween = [];

// For each diff day, we get the next one)
for (let i = 0; i <= diff; i++) {
  // use % to loop to beginning again (e.g: start at friday and have +4)
  weekdaysBetween.push(moment.weekdays((firstDay + i) % 7));
}

return weekdaysBetween;

You can also check a working demo version here

Upvotes: 0

Eric
Eric

Reputation: 169

let start = moment(startDate, 'YYYY-MM-DD'); //Pick any format
let end = moment(); //right now (or define an end date yourself)
let weekdayCounter = 0;  

while (start <= end) {
 if (start.format('ddd') !== 'Sat' && start.format('ddd') !== 'Sun'){
   weekdayCounter++; //add 1 to your counter if its not a weekend day
 }
 start = moment(start, 'YYYY-MM-DD').add(1, 'days'); //increment by one day
}
console.log(weekdayCounter); //display your total elapsed weekdays in the console!

Upvotes: 5

Joon
Joon

Reputation: 9884

You are going to need to write your own function for this.

It is not that hard since you know exact start and end dates.

  1. get what day in a week it is for both start and end dates.
  2. count only week days between the two.

I think it is going to be pretty straight forward implementation.

Upvotes: 3

Related Questions