简体   繁体   English

JavaScript获取下一个星期二或星期五的日期(最近)

[英]Javascript get date of next tuesday or friday (closest)

I need to code a function that returns the date (example: 2014/08/28) of next tuesday or next friday, whichever is the closest day. 我需要编写一个函数,该函数返回下一个星期二或下一个星期五的日期(例如:2014/08/28),以最近的日期为准。 But there is a little quibble: if today's day is tuesday or friday, if it is before 22:00 it should return todays date, on the other hand if it's after 22:00 or equal to 22:00 it should return next tuesday's or friday's date, whichever it's the next one. 但是有一点疑问:如果今天是星期二或星期五,如果是22:00之前,则应返回今天的日期,另一方面,如果是22:00或等于22:00,则应返回下一个星期二或星期五的日期,以下一个为准。

I've no clue on how to start coding this. 我不知道如何开始编码。

Regards, 问候,

Check the sninppet below. 检查下面的sninppet。 Maybe I could make it more optimised but more or less, I just followed the pseudo-code from the comments above. 也许我可以使它更优化,但是或多或少,我只是遵循上面注释中的伪代码。

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());

Working jsBin 工作jsBin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM