【问题标题】:Get All Monday Dates In Month using Moment,js使用 Moment,js 获取月份中的所有星期一日期
【发布时间】:2015-11-09 23:18:23
【问题描述】:

有没有办法使用moment.js库获取当前月份的所有星期一日期。

我知道我可以通过:

moment().endOf('month')

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

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

【问题讨论】:

标签: javascript jquery momentjs


【解决方案1】:

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

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

【讨论】:

  • 编辑了您的答案,使其适用于所有月份。问题是,.day("Monday") 实际上可以向后移动到上个月,这取决于月份边界在一周内的落入方式,因此您必须对此进行测试。然后,.add(7,'d') 更简洁,因为如果需要,可以在一个地方更改星期几。
【解决方案2】:

更新

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

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

然后:

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

等 - 随时查看source

旧帖

这个功能应该可以工作:

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,修改为包含自定义日期参数。

【讨论】:

  • 感谢您的加入。尽管这些方法存在一些错误,您能否打开问题列表或允许 PR?
  • @webnoob - 这是一个要点 - 所以它不接受 prs。随意分叉和改变它,我会修改答案:)
【解决方案3】:

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

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

moment().weekdaysInMonth('Monday');

【讨论】:

  • 感谢这个插件。它真的很简单而且效果很好。
猜你喜欢
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多