我有一个JavaScript函数,可以确定下一个工作日的日期。除周日外,它适用于所有日子。
For Sunday:
Sun May 25 2014
Sun Jun 08 2014
Sun Jun 22 2014
For Saturday:
Sat May 24 2014
Sat May 31 2014
Sat Jun 07 2014
Sat Jun 14 2014
function getDatesByweekDay(weekday){
var startdate = new Date();
var date2 = new Date();
lastday = new Date(date2.setDate(date2.getDate() + 28 + weekday - date2.getDay()));
var dates = Array();
var x = 0;
do {
startdate = new Date(startdate.setDate(startdate.getDate() + 7 + weekday - startdate.getDay()));
console.log(startdate);
var date = new Date();
var curr_date = startdate.getDate();
var curr_month = startdate.getMonth() + 1;
var curr_year = startdate.getFullYear();
var formattedDate = curr_year + "-" + curr_month + "-" + curr_date;
dates[x] = formattedDate;
x++;
} while(lastday > startdate);
return dates;
}
getDatesByweekDay(6);
答案 0 :(得分:3)
它不工作的原因是因为你在7天工作周的第8天通过了。如果你从14到20传递一个数字,那么在返回的日期之间它会跳过两周而不是一周。
问题与do...while
的第一行有关:
startdate = new Date(startdate.setDate(startdate.getDate() + 7 + weekday - startdate.getDay()));
您正在添加7以提前1周,加上工作日,减去开始日期的星期几。如果您的weekday
变量为1周或更长时间,那么它将提前一周以上。因为它应该是0到6之间的数字,并且你在7中传递,你就会遇到这个错误。
您可以通过几种不同的方式修复它,但只需将输入weekday
标准化为0-6的数字即可解决问题。在函数开头附近添加weekday = weekday % 7;
。
答案 1 :(得分:2)
致电
getDatesByweekDay(0);
它似乎会返回您正在查看的正确信息。