javascript - 如何从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
以上将返回当前月份的星期一。有人可以帮帮我吗?
提前致谢。
解决方案
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; }
推荐阅读
- django - 在 django admin 中自动注册某些模型的问题
- python - 如何使用 Numpy 有效地创建条件列数组?
- javascript - 如何在nodejs中形成一个动态的json数组?
- postgresql - 是否可以保证 postgres 中并行聚合函数的最小工作人员数量?
- java - 如何将 YML 值放入 @Pattern(regexp = "HELLO|WORLD")
- vb.net - 如何使用 PostgreSQL 作为数据库和 vb.net windows 窗体在 DataGridView1 中发布数据
- python - 如何为具有扩展用户(onetoone 字段)关系的模型执行 put/patch 方法 django rest框架
- jquery - 从 ajax 调用传回的数据中选择特定项目
- sql - 简化 Oracle 中的现有查询
- c# - 在我给它一个输入之后,我的程序一直跳到 else 语句。我已经尝试了一些东西,但没有任何工作。(C#)