如何在一个月内循环工作日?

时间:2015-05-21 22:51:33

标签: javascript

monthDays = 31;
dayOfMonth = 9;
weekOfMonth = 2;

startDay = weekStartingDate (weekOfMonth); // function return 8

// startDay could be 8, 15, 22 or 28
for (var day = startDay; day < (startDay+7) ; day++)
{
     //stuff
}

问题是,当startDay为29岁时,(startDay+7)取代monthDays

考虑到工作日范围,我想循环几天。

5 个答案:

答案 0 :(得分:2)

您应该为for循环定义限制值

for (var day = startDay; day < ((startDay+7) > monthDays ? monthDays : (startDay+7)) ; day++)
{
     //stuff
}

答案 1 :(得分:1)

monthDays = 31;
dayOfMonth = 9;
weekOfMonth = 2;

startDay = weekStartingDate (weekOfMonth); // function return 8
for (var day = startDay; day < (startDay+7) ; day++)
{
     //stuff
  if(x >=31 ){
  break; 
         }
}

答案 2 :(得分:1)

为什么不使用大学?

monthDays = 31;
dayOfMonth = 9;
weekOfMonth = 2;

startDay = weekStartingDate (weekOfMonth); // function return 8
var maxDay = (startDay+7) > monthDays ? monthDays : (startDay+7)
// startDay could be 8, 15, 22 or 28
for (var day = startDay; day <= maxDay ; day++)
{
     //stuff
}

答案 3 :(得分:0)

而不是(startDay+7)使用(startDay+7)%monthDays

答案 4 :(得分:0)

不太确定您要做什么,但似乎您正在尝试获取同月的一周的日期。

以下功能可以做到这一点。 getWeekStartDate 返回给定日期的星期开始日期,可选择从星期一或星期日开始。 getNext7DatesInMonth 从同一个月的给定日期起最多7天。

结果是所需日期的数字数组。

/*
** @param {Date} date
** @param {boolean} weekStartsOnMon - true if week starts on Monday
** @returns {Date} - new date object for first day of week
*/
function getWeekStartDate(date, weekStartsOnMon) {
  var d = new Date(+date);
  var dayNum = d.getDay();

  // If start of week is Monday
  if (weekStartsOnMon) {
    d.setDate(d.getDate() - (dayNum? dayNum : 7) +1)
    ;
  // If start of week is Sunday
  } else {
    d.setDate(d.getDate() - d.getDay());
  }
  return d;
}

/*
** For the given date, get the dates in the week for the same month.
**
** @param {Date} date
** @param {boolean} weekStartsOnMon - true if week starts on Monday
** @returns {Array} - String dates for rest of week in same month as date
*/
function getNext7DatesInMonth(date){
  var start = new Date(+date);
  var monthNum = start.getMonth();
  var weekDates = [];
  var i = 7;

  while (monthNum == start.getMonth() && i--) {
    weekDates.push(start.getDate());
    start.setDate(start.getDate() + 1);
  }
  return weekDates;
}

// Start week on Sunday
var d = new Date(2015,4,31)
console.log(d + ': ' + getNext7DatesInMonth(getWeekStartDate(d, false))); // 31

// Start week on Monday
var d = new Date(2015,4,31)
console.log(d + ': ' + getNext7DatesInMonth(getWeekStartDate(d, true))); // 25,26,27,28,29,30,31

你可以在没有Date对象的情况下执行类似的功能,这取决于获取当月的天数,但Date对象很方便。