我将从日历中选择日期范围说例如我将从 6月6日到7月26日选择日期范围。我需要计算星期二和星期四的数量< / strong>在所选范围内
答案 0 :(得分:1)
您可以使用时刻库(http://momentjs.com轻松完成此操作,您可以使用 npm安装时刻将其添加到项目中,然后将其导入到您需要的组件中。)
countDays = () => {
let { date1, date2 } = this.state;
let tuesdays = 0,
thursdays = 0;
date1 = moment(date1);
date2 = moment(date2);
let fromDayWeek = date1.isoWeeks();
let toDayWeek = date2.isoWeeks();
let fromDay = date1.isoWeekday();
let toDay = date2.isoWeekday();
let weekIteration = toDayWeek - fromDayWeek;
let j = 1,
daysOfWeek = 7;
for (let i = 0; i <= weekIteration; i++) {
// iterating throught days - first day = 1 = monday, last day = 7 = sunday
j = i === 0 ? fromDay : 1; // we want to start counting for the first selected date
daysOfWeek = i === weekIteration - 1 ? toDay : 7; // we want to end counting for the last selected date
for (j; j <= daysOfWeek; j++) {
// if it's tuesday, it is 2 day of week
if (j === 2) {
tuesdays++;
}
// if it's thursday, it is 4 day of week
if (j === 4) {
thursdays++;
}
}
}
return {
tuesdays,
thursdays
};
};
请点击此处查看完整的解决方案: https://codesandbox.io/s/x2w6nq6npq
答案 1 :(得分:0)
然而,这可以简化,但这是最简单的方法。
我假设您有范围的Datepickers,例如假设 -
<input type="date" name="from"/>
<input type="date" name="to"/>
现在我们从输入中获取日期作为值并循环通过 -
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
tuesdays=[],
mondays=[];
$('button').click(function(){
var startDate = new Date($('input[name="from"]').val()),
endDate = new Date($('input[name="to"]').val());
while(startDate <= endDate){
var dayName = days[new Date(startDate).getDay()];
if(dayName==="Monday"){
mondays.push(new Date(startDate));
}
if(dayName ==="Tuesday"){
tuesdays.push(new Date(startDate));
}
startDate = new Date(startDate).setDate(new Date(startDate).getDate() + 1);
}
});
浏览开始日期和结束日期并获取日期名称。
看看我为你做的这个小提琴 - http://jsfiddle.net/xpvt214o/220346/
P.S。如果需要,请确保将StartDate的验证低于EndDate和其他人。这只是一个从它开始的例子。