我需要编写一个函数来返回下周二或下周五的日期(例如:2014/08/28),以最接近的那一天为准。但是有一点小问题:如果今天是星期二或星期五,如果它在 22:00 之前,它应该返回今天的日期,另一方面,如果它在 22:00 之后或等于 22:00,它应该返回下一个星期二或星期五的日期,以下一个为准。
我不知道如何开始编写代码。
问候,
最佳答案
检查下面的代码段。也许我可以让它更优化,但或多或少,我只是按照上面评论中的伪代码。
function closest_tuesday_or_friday() {
var today = new Date(), tuesday, friday, day, closest;
if(today.getDay() == 2 || today.getDay() == 5){
if(today.getHours() < 22){
return today.getFullYear() + "/" + (today.getMonth() + 1) + "/" + today.getDate();
}
}else{
day = today.getDay();
tuesday = today.getDate() - day + (day === 0 ? -6 : 2);
friday = today.getDate() - day + (day === 0 ? -6 : 5);
}
if(tuesday < friday){
closest = new Date(today.setDate(tuesday));
}else{
closest = new Date(today.setDate(friday));
}
return closest.getFullYear() + "/" + (closest.getMonth() + 1) + "/" + closest.getDate();
}
console.log(closest_tuesday_or_friday());
关于Javascript 获取下周二或周五的日期(最近的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25492523/