用于显示即将到来的每两个星期五的日期的脚本

时间:2019-06-27 00:50:47

标签: javascript

截止日期:截止日期设为下一个双月星期五(例如,截止日期为6月14日和6月28日。如果今天(6月26日)完成提交,则截止日期为6月28日。提交的日期为6月29日,截止日期为7月12日。一旦截止日期为7月13日,下一个截止日期将为7月26日。依此类推,具体取决于用户提交表单的时间,它将显示正确的截止日期。环顾了其他几个示例,但找不到我想要的示例。

var currentDate = new Date(new Date().getTime())
document.getElementById('lastsubmission').value =
  (currentDate.getDate()) + '/' + (currentDate.getMonth() + 1) + '/' +
  currentDate.getFullYear() + '@' + currentDate.getHours() + ':' +
  currentDate.getMinutes() + ':' + currentDate.getSeconds();

1 个答案:

答案 0 :(得分:0)

您似乎想在一个月的第二个或第四个星期五之后的下一个星期五得到一个星期五。像这样:

  1. 获取日期月份的第二个星期五
  2. 如果在此之前,请返回第二个星期五
  3. 如果在那之后,请获取该月的第四个星期五
  4. 如果在那之前,请返回第四个星期五
  5. 如果在那之后,请返回下个月的第二个星期五

因此,您可能需要一个函数来获取给定日期的特定星期五,以及其他一些代码来执行其余的逻辑,例如

// Given a Date, return the nth Friday of that month
function getNthFriday(date, n) {
  // Get first Friday
  let d = new Date(date);
  d.setDate(1);
  let day = d.getDay();
  d.setDate(d.getDate() + 5 - (day > 5? -1 : day));
  // Set to nth Friday
  d.setDate(d.getDate() + (n-1)*7);
  return d;
}

// Return the next Friday after date that is either the
// second or fourth Friday's of a month.
function getCutoffDate(date) {
  // Get 2nd Friday
  var friday = getNthFriday(date, 2);
  // If before, return 2nd Friday
  if (date < friday) {
    return friday;
  }
  // Get 4th Friday
  friday = getNthFriday(date, 4);
 
  // If before, return 4th Friday
  if (date < friday) {
    return friday;
  }
  // Otherwise, return 2nd Friday of next month  
  friday = getNthFriday(new Date(date.getFullYear(), date.getMonth()+1, 1), 2);
  return friday;
}

// Some tests
[
 new Date(2019,4,30), // 30 May 2019 -> 14 Jun
 new Date(2019,5, 1), //  2 Jun 2019 -> 14 Jun
 new Date(2019,5,13), // 13 Jun 2019 -> 28 Jun
 new Date(2019,5,23), // 23 Jun 2019 -> 14 Jun
 new Date(2019,5,30)  // 30 Jun 2019 -> 12 Jul
].forEach(d => {
  console.log(getCutoffDate(d).toString());
});

图书馆可能有助于获取第n个星期五,并获取下个月的第一天。