首页 > 解决方案 > 如何从javascript获取当前一周的星期一和接下来的五个星期一

问题描述

我想从本周到接下来的五个星期一获取星期一列表。我试着在本月得到它。但是,如果日期是本月的最后一天,它应该给出那个星期一的日期和接下来的五个星期一的日期。

这是我尝试过的代码。

var Mondays = [];
var month = new Date().getMonth();
while (d.getMonth() === month) {
    mondays.push(new Date(d.getTime()));
    d.setDate(d.getDate() + 7);
}
return mondays

以上将返回当前月份的星期一。有人可以帮帮我吗?

提前致谢。

标签: javascriptdate

解决方案


function isDate(type) {
  return (/^\[object\s+Date\]$/).test(
    Object.prototype.toString.call(type)
  );
}

function getAllMondaysFromDate(count, date) {
  count = parseInt(count, 10);
  count = Number.isNaN(count)
    ? 1
    // prevent negative counts and limit counting to
    // approximately 200 years into a given date's future.
    : Math.min(Math.max(count, 0), 10436);

  // do not mutate the date in case it was provided.
  // thanks to RobG for pointing to it.
  date = (isDate(date) && new Date(date.getTime())) || new Date();

  const listOfMondayDates = [];
  const mostRecentMondayDelta = ((date.getDay() + 6) % 7);

  date.setDate(date.getDate() - mostRecentMondayDelta);

  while (count--) {
    date.setDate(date.getDate() + 7);

    listOfMondayDates.push(
      new Date(date.getTime())
    );
  }
  return listOfMondayDates;
}

// default ...
console.log(
  'default ...',
  getAllMondaysFromDate()
);

// the next upcoming 5 mondays from today ...
console.log(
  'the next upcoming 5 mondays from today ...',
  getAllMondaysFromDate(5)
    .map(date => date.toString())
);

// the next 3 mondays following the day of two weeks ago ...
console.log(
  'the next 3 mondays following the day of two weeks ago ...',
  getAllMondaysFromDate(3, new Date(Date.now() - (14 * 24 * 3600000)))
    .map(date => date.toString())
);

// proof for not mutating the passed date reference ...
const dateNow = new Date(Date.now());

console.log(
  'proof for not mutating the passed date reference ...\n',
  'before :: dateNow :',
  dateNow
);
console.log(
  'invoke with `dateNow`',
  getAllMondaysFromDate(dateNow)
);
console.log(
  'proof for not mutating the passed date reference ...\n',
  'after :: dateNow :',
  dateNow
);
.as-console-wrapper { min-height: 100%!important; top: 0; }


推荐阅读