【问题标题】:Moment.js not displaying all dates correctlyMoment.js 未正确显示所有日期
【发布时间】:2015-09-04 00:06:12
【问题描述】:

我正在尝试使用 Moment.js 显示下一个即将到来的星期四,但不确定为什么中间日期会跳过。例如:代替显示:Sep 3, 10, 17, 24, Oct 1

改为显示 9 月 3 日、10 日、24 日、10 月 15 日、11 月 12 日、12 月 17 日等...

这是我目前所拥有的:

var date = moment();
var y = 3;
while (y<56) {
   var nextThursday = date.weekday(y).add(1,"days").format("dddd, MMM Do");
   var addValueThursday = nextThursday;
   var thurs = {"text": addValueThursday};
   console.log(addValueThursday);
   y+=7;
}

【问题讨论】:

    标签: javascript date momentjs


    【解决方案1】:

    我相信答案可以在 add 函数的作用中找到:通过添加时间来改变原始时刻

    所以你继续增加一个已经增加(通过突变)的日期。

    一种解决方案是重置循环内的日期:

    var y = 3;
    while (y<56) {
        var date = moment();
        var nextThursday = date.weekday(y).add(1,"days").format("dddd, MMM Do");
        var addValueThursday = nextThursday;
        var thurs = {"text": addValueThursday};
        console.log(addValueThursday);
        y+=7;
    }
    

    这给出了以下输出:

    Thursday, Sep 3rd
    Thursday, Sep 10th
    Thursday, Sep 17th
    Thursday, Sep 24th
    Thursday, Oct 1st
    Thursday, Oct 8th
    Thursday, Oct 15th
    Thursday, Oct 22nd
    

    可能有更聪明的方法可以做到这一点,但我对 moment 库不是很熟悉。

    【讨论】:

      【解决方案2】:

      从本周开始,我将如何找到接下来 10 次出现的星期四:

         var thursday = moment().startOf('week').add(4, 'days');
      
         for (var i=0; i<10; i++) {
           console.log(thursday.format("dddd, MMM Do"));
           thursday = thursday.add(1, 'week');
         }
      

      这将console.log 类似于:

      Thursday, Sep 3rd
      Thursday, Sep 10th
      Thursday, Sep 17th
      Thursday, Sep 24th
      Thursday, Oct 1st
      Thursday, Oct 8th
      Thursday, Oct 15th
      Thursday, Oct 22nd
      Thursday, Oct 29th
      Thursday, Nov 5th
      

      jsbin:https://jsbin.com/gojetisawu/1/edit?html,output

      【讨论】:

      • 这看起来更聪明。您可以跳过thursday = thursday.add(1, 'week'); 中的赋值部分,只需执行thursday.add(1, 'week');,因为该方法会改变它所调用的对象。
      猜你喜欢
      • 2016-06-07
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多