如何返回给定工作日的下一个日期(它可以是数字 0-6 或名称星期日至星期六)。
例如,如果今天,在2009 年 10 月 16 日星期五, 我通过了:
- Friday,它将返回今天的日期2009 年 10 月 16 日
- 星期六返回2009 年 10 月 17 日
- 周四返回2009 年 10 月 22 日
如何返回给定工作日的下一个日期(它可以是数字 0-6 或名称星期日至星期六)。
例如,如果今天,在2009 年 10 月 16 日星期五, 我通过了:
仅添加 7 并不能解决问题。
以下功能将为您提供一周的第二天。
function nextDay(x){
var now = new Date();
now.setDate(now.getDate() + (x+(7-now.getDay())) % 7);
return now;
}
这是蒂姆回答特定问题的稍微修改的版本——传入日期 d,以及所需的星期几(0-6 日),返回日期
function nextDay(d, dow){
d.setDate(d.getDate() + (dow+(7-d.getDay())) % 7);
return d;
}
这是另一个简单的解决方案
//takes dayIndex from sunday(0) to saturday(6)
function nextDate(dayIndex) {
var today = new Date();
today.setDate(today.getDate() + (dayIndex - 1 - today.getDay() + 7) % 7 + 1);
return today;
}
document.write("Next Sunday is: "+nextDate(0).toLocaleString()+"<br/>");
document.write("Next Thursday is: "+nextDate(4).toLocaleString()+"<br/>");
document.write("Next Saturday is: "+nextDate(6).toLocaleString());
为了扩展用户 190106的答案,这段代码应该给你你想要的:
function getNextDay(day, resetTime){
var days = {
sunday: 0, monday: 1, tuesday: 2,
wednesday: 3, thursday: 4, friday: 5, saturday: 6
};
var dayIndex = days[day.toLowerCase()];
if (dayIndex !== undefined) {
throw new Error('"' + day + '" is not a valid input.');
}
var returnDate = new Date();
var returnDay = returnDate.getDay();
if (dayIndex !== returnDay) {
returnDate.setDate(returnDate.getDate() + (dayIndex + (7 - returnDay)) % 7);
}
if (resetTime) {
returnDate.setHours(0);
returnDate.setMinutes(0);
returnDate.setSeconds(0);
returnDate.setMilliseconds(0);
}
return returnDate;
}
alert(getNextDay('thursday', true));
如果您不想通过数字而是通过工作日名称(星期日 - 星期六)来查找某个工作日的未来日期,那么这也可以帮助您:
function getDateOfWeekday(refday){
var days = {
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
sunday: 0
};
if(!days.hasOwnProperty(refday))throw new Error(refday+" is not listed in "+JSON.stringify(days));
var currDate = new Date();
var currTimestamp = currDate.getTime();
var triggerDay = days[refday];
var dayMillDiff=0;
var dayInMill = 1000*60*60*24;
// add a day to dayMillDiff as long as the desired refday (sunday for instance) is not reached
while(currDate.getDay()!=triggerDay){
dayMillDiff += dayInMill;
currDate = new Date(currDate.getTime()+dayInMill);
}
return new Date(currTimestamp + dayMillDiff);
}
var sunday = getDateOfWeekday("sunday");
document.write("Next Sunday is at: <strong>"+sunday.toLocaleString()+"</strong><br/>");
var thursday = getDateOfWeekday("thursday");
thursday.setHours(0,0,0,0); // set hours/minutes/seconds and millseconds to zero
document.write("Next Thursday is at: <strong>"+thursday.toLocaleString()+"</strong> on midnight<br/>");
var tuesday = getDateOfWeekday("tuesday");
document.write("Next Tuesday is at: <strong>"+tuesday.toLocaleString()+"</strong><br/>");