如何在给定时间内找到周一

How to find Monday with given time?

本文关键字:周一 定时间      更新时间:2023-09-26

无论哪一天,我都在努力寻找周一。它有两个要求。

例如:

1. If given day is Monday through Friday, find the last closest Monday, 
   so if the given day is 10-31, I need to get 10-27
2. If given day is Saturday or Sunday, find the next Monday.

JavaScript:

var today = new Date(); //assuming it's 11/1/2014 Saturday
var todayDay = today.getDay(); > 6

if(todayDay == 6) {
    var Monday = today.getDate() + 2;
}    

我不知道如何动态地找到星期一的日期和时间。我已经查找了javascript day方法,但不知道如何获得它。有人能帮我吗?谢谢

因此,重新表述您的要求是:给定一周从周日开始,找到该周中的周一。

使用moment.js太容易了。。。

本周的周日

moment().startOf('week')

所以找到星期一做

moment().startOf('week').add('days', 1)

编辑

您可以使用以下时刻函数更改周初

moment.lang('en-in', {
    week : {
        dow : 1 // Monday is the first day of the week
    }
});

而获取索引的星期几数组是

   daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],

javscript的Date对象具有方法getDay()、setDate()和getDate(),这些方法对此很有帮助。

"use strict";
var d = document.getElementById('d');
var mon = document.getElementById('mon');
var handleDatePick = function(ev){
  var the_date = new Date(d.value);
  if (the_date.getDay() <= 4) {
      the_date.setDate( the_date.getDate() - the_date.getDay() );
  } else {
    the_date.setDate( the_date.getDate() + 7 - the_date.getDay() );
  }
  var output = 'the nearest monday is ' + the_date.toUTCString();
  mon.value = output;
};
d.addEventListener('input',handleDatePick);
input, output {
  display: block;
  clear: both;
}
pick the date: <input type="date" id="d" />
<output id="mon" for="d"></output>