javascript 使用 Moment,js 获取本月的所有星期一日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33620161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get All Monday Dates In Month using Moment,js
提问by Shan Khan
Is there any way to get all the Monday DATES in the current month using moment.js library.
有没有办法使用moment.js库获取当月的所有星期一日期。
I know I can get the end of the month with:
我知道我可以通过以下方式获得月底:
moment().endOf('month')
but how to get all monday dates of current / any month.
但是如何获取当前/任何月份的所有星期一日期。
I dont want some function in javascript default date library. Please refer the code using Moment Js Library.
我不想要 javascript 默认日期库中的某些功能。请参考使用 Moment Js 库的代码。
回答by Danil Gudz
I've just read docs and haven't found any method that returns an array, so you need to do it only with loop
我刚刚阅读了文档,还没有找到任何返回数组的方法,所以你只需要使用循环来做
var monday = moment()
.startOf('month')
.day("Monday");
if (monday.date() > 7) monday.add(7,'d');
var month = monday.month();
while(month === monday.month()){
document.body.innerHTML += "<p>"+monday.toString()+"</p>";
monday.add(7,'d');
}
回答by Ben Aubin
Update
更新
I made a little drop infor this. Add it to your page:
我做了一个小的下降这一点。将其添加到您的页面:
<script src="https://gist.github.com/penne12/ae44799b7e94ce08753a/raw/moment-daysoftheweek-plus.js"></script>
And then:
接着:
moment().allDays(1) //=> [...]
moment().firstDay(1)
etc - feel free to check out the source
等 - 随时查看源
Old Post
旧帖
This function should work:
这个功能应该工作:
function getMondays(date) {
var d = date || new Date(),
month = d.getMonth(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays;
}
Usage: getMondays()
for this month, or getMondays(moment().month("Feb").toDate())
for a different month.
用法:getMondays()
本月或getMondays(moment().month("Feb").toDate())
不同月。
From jabclab's Stack Overflow Answer, modified to include custom date param.
来自jabclab 的 Stack Overflow Answer,修改为包含自定义日期参数。
回答by Kodie Grantham
I know this is old but this is the first thing that comes up in Google.
我知道这是旧的,但这是谷歌出现的第一件事。
You can get all the Mondays in the month by using my moment-weekdaysinmoment.js plugin:
您可以使用我的moment-weekdaysin moment.js 插件获取该月的所有星期一:
moment().weekdaysInMonth('Monday');