admin 管理员组文章数量: 1086019
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 (/) 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!
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./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!
3 Answers
Reset to default 5let 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!
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.
- get what day in a week it is for both start and end dates.
- count only week days between the two.
I think it is going to be pretty straight forward implementation.
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
本文标签: javascriptGet Elapsed Weekdays Between Two Dates Using MomentJSStack Overflow
版权声明:本文标题:javascript - Get Elapsed Weekdays Between Two Dates Using MomentJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744055251a2525733.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论