javascript - 第二天去,跳过周末

标签 javascript date datetime weekday

我想使用 JavaScript 生成下一个工作日。

这是我现在的代码

var today = new Date();
    today.setDate(today.getDate());
    var tdd = today.getDate();
    var tmm = today.getMonth()+1;
    var tyyyy = today.getYear();

    var date = new Date();

    date.setDate(date.getDate()+3);

问题是,在星期五它返回星期六的日期,而我希望它是星期一

最佳答案

这将选择下一个工作日。

var today = new Date(2016, 7, 26,12,0,0,0,0); // Friday at noon
console.log("today, Monday",today,"day #"+today.getDay());
var next = new Date(today.getTime());
next.setDate(next.getDate()+1); // tomorrow
while (next.getDay() == 6 || next.getDay() == 0) next.setDate(next.getDate() + 1);
console.log("no change    ",next,"day #"+next.getDay());
console.log("-------");
// or without a loop:

function getNextWork(d) {
  d.setDate(d.getDate()+1); // tomorrow
  if (d.getDay()==0) d.setDate(d.getDate()+1);
  else if (d.getDay()==6) d.setDate(d.getDate()+2);
  return d;
}
next = getNextWork(today); // Friday
console.log("today, Friday",today);
console.log("next, Monday ",next);
console.log("-------");
today = new Date(2016, 7, 29,12,0,0,0); // Monday at noon
next = getNextWork(today);              // Still Monday at noon
console.log("today, Monday",today);
console.log("no change    ",next);
console.log("-------");

// Implementing Rob's comment

function getNextWork1(d) {
  var day = d.getDay(),add=1;
  if (day===5) add=3;
  else if (day===6) add=2;
  d.setDate(d.getDate()+add);  
  return d;
}
today = new Date(2016, 7, 26,12,0,0,0,0); // Friday at noon
next = getNextWork1(today);               // Friday
console.log("today, Friday",today);
console.log("next, Monday ",next);
console.log("-------");
today = new Date(2016, 7, 26,12,0,0,0,0); // Monday at noon
next = getNextWork1(today); // Monday
console.log("today, Monday",today);
console.log("no change    ",next);

关于javascript - 第二天去,跳过周末,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39137913/

相关文章:

php - 使用 javascript 获取 session

javascript - 如果我在 JavaScript 中有像 1325982833403 这样的时间,如何将其转换为 datejs 值?

javascript - 使用 Object.assign() 合并数据并创建数组

mysql - 我认为 curtime()、now() 和 current_timestamp 是 MySql 中有效的默认日期时间值?

javascript - 如何在文本区域前添加一些文本

java - 为什么 setLastModified(time) 不适用于此文件?

mysql - SQL排序月份升序和月份降序?

c# - 按周数获取日期范围c#

javascript - 将日期时间格式设置为 DD-MM YYYY HH :mm:ss using moment. js

python - 将字符串转换为日期时间 pandas