如何获得一周的星期一作为数字

时间:2016-03-18 16:55:54

标签: javascript

我想在某一年中获得一周的第一天(假设星期一开始一周)。

场景:年份是2016年。它应该返回4,因为星期一 2016年1月4日是2016年第1周的第一天。

我该怎么做?我想要这样的东西:

var date = new Date();
var week = 1;
var year = 2016;
date.getMonday(week, year); // 4 (because 04/01/2016 is a Monday and is week number 1)

week = 5;
date.getMonday(week, year); // 30 (because 30/01/2016 is a Monday and is week number 5)

由于

3 个答案:

答案 0 :(得分:3)

您可以使用JavaScript的var output = document.getElementById('output'); var year = 2016; var firstMonday = new Date(year, 0, 1); // year, month (zero-index), date // starting at January 1st, increment the date until a Monday (`getDay() = 1`) while(firstMonday.getDay() !== 1) { firstMonday.setDate(firstMonday.getDate() + 1); } // output the date of the first Monday in January output.value = firstMonday.getDate();方法来确定日期对象所指的星期几。



<textarea id="output"></textarea>
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我已经找到了解决这个问题的功能......见下文

function getDayInWeek(dayOfWeek, week, year){
   dayOfWeek = dayOfWeek % 7; //ensure day of week
   var baseDate = new Date(year, 0, 1); //get the first day
   var firstDayOfWeek = baseDate.getDay(); //get the first week day
   var inWeek = (week - 1) * 7; //get the days to start of week
   var diff = firstDayOfWeek - dayOfWeek; //get the diff for day in that week
   if(diff < 0) diff += 7;
   baseDate.setDate(inWeek + diff);
   return baseDate.getDate(); //get the month day

}

使用指定工作日

// 0 = sunday
// 1 = monday
// 2 = tuesday
// 3 = wednesday
// 4 = thursday
// 5 = friday
// 6 = saturday
var firstMonday = getDayInWeek(1, 1, 2016); // the monday in first week of 2016

var mondayOf5 = getDayInWeek(1, 5, 2016); // the monday in 5th week of 2016

答案 2 :(得分:0)

要获得ISO-8601周,这将始终是星期一,请参阅链接:  Wikipedia  Calculate ISO 8601

&#13;
&#13;
function getISOWeek(week, year) {
  var _date = new Date(year, 0, 1 + (week - 1) * 7);
  var date_of_week = _date.getDay();
  var ISOweekStart = _date;
  (date_of_week <= 4) ? ISOweekStart.setDate(_date.getDate() - _date.getDay() + 1): ISOweekStart.setDate(_date.getDate() + 8 - _date.getDay());
  return ISOweekStart;
}
console.log(getISOWeek(10, 2016));
&#13;
&#13;
&#13;