使用 Moment,js 获取一个月中的所有星期一日期

Get All Monday Dates In Month using Moment,js

有没有什么方法可以使用 moment.js 库获取当月所有星期一的日期。

我知道我可以通过以下方式获得月底:

moment().endOf('month')

但是如何获取当前/任何月份的所有星期一日期。

我不需要 javascript 默认日期库中的某些功能。请参考使用 Moment Js 库的代码。

更新

我为此做了一点drop in。将其添加到您的页面:

<script src="https://gist.github.com/penne12/ae44799b7e94ce08753a/raw/moment-daysoftheweek-plus.js"></script>

然后:

moment().allDays(1) //=> [...]
moment().firstDay(1)

等-随时查看source

旧Post

这个函数应该可以工作:

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;
}

用法:getMondays() 表示本月,或 getMondays(moment().month("Feb").toDate()) 表示其他月份。

来自 jabclab's Stack Overflow Answer,已修改为包含自定义日期参数。

我刚刚阅读了文档,还没有找到任何 returns 数组的方法,所以你只需要使用循环

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');
}

check this out

我知道这是旧的,但这是 Google 中出现的第一件事。

您可以使用我的 moment-weekdaysin moment.js 插件获取一个月中的所有星期一:

moment().weekdaysInMonth('Monday');