MomentJS范围并不总是包括当前月份的日期范围

时间:2015-11-18 15:21:46

标签: javascript date momentjs date-range

由于一些奇怪的原因,MomentJS范围并不总是显示当前月份。我想知道是否有一个选项需要设置,以便它包括当前月份的日期范围。

这是用于生成日期范围的代码。我还附上了一个编码器,以便您可以看到它的实际效果。

http://codepen.io/anon/pen/rORmxY

    //momentJs creates the ranges
    //Only shows April 2015
    var end = moment("2015-05-01","YYYY-MM-DD");
    //where the day is > 18 it Shows May 2015
    var end2 = moment("2015-05-19","YYYY-MM-DD");
    var start = moment().subtract(1.5, "year");
    var range = moment.range(start, end); 
    var range2 = moment.range(start, end2); 

    //iterate through the months, and populate the SELECT box
    range.by('months', function(date) {
      //add those values to a SELECT box
      $('#month-range').prepend($('<option>', {
        value: date.format("MMM YYYY"),
        text: date.format("MMM YYYY")
      }));
    });

   //iterate through the months, and populate the SELECT box
    range2.by('months', function(date) {
      //add those values to a SELECT box
      $('#month-range2').prepend($('<option>', {
        value: date.format("MMM YYYY"),
        text: date.format("MMM YYYY")
      }));
    });

非常感谢

2 个答案:

答案 0 :(得分:1)

请查看月份范围(https://github.com/gf3/moment-range/blob/master/lib/moment-range.js)的源代码。

将结束日期设定为2015-05-18的原因将包括少于一个月,因为2015-05-19并不特别。因为今天是2015-11-18而且您将开始日期设置为2014-05-18。

现在看一下时刻范围内的_byString函数(由&#39; by&#39;函数调用)。

function _byString(interval, hollaback, exclusive) {
  var current = moment(this.start);

  while (this.contains(current, exclusive)) {
    hollaback.call(this, current.clone());
    current.add(1, interval);
  }
}

&#39;电流&#39;变量从2014-05-18&#39;开始并且一次增加一个月。 如果结束日期是2015-05-19,那么这个包含()&#39;当&#39;当前&#39;时简单地返回true =&#39; 2015-05-18&#39;。如果结束日期是2015-05-19,那么这就是&#39; this.contains&#39;将返回false。这就是您的代码行为的原因。

现在,如果您想要总是包含当前月份,我认为您总是在结束日期添加1天。但是,我想这个方法可能会导致一个月的最后一天出现问题。或者您始终可以将结束日期设置为下个月的第一天,但​​不包括该月份。你可以做一些实验。

希望这有帮助!

答案 1 :(得分:1)

我发现的工作就是简单告诉momentJs使用月末作为范围。这在这方面是有道理的。这是通过将.endOf(&#34; month&#34;)添加到结束范围来完成的。

请参阅此代码以获得澄清:

//momentJs creates the ranges
//adding .endOf("month") will Include the month of May in the month ranges
var end = moment("2015-05-01","YYYY-MM-DD").endOf("month");
var start = moment().subtract(1.5, "year");
var range = moment.range(start, end); 

//iterate through the months, and populate the SELECT box
range.by('months', function(date) {
  //add those values to a SELECT box
  $('#month-range').prepend($('<option>', {
    value: date.format("MMM YYYY"),
    text: date.format("MMM YYYY")
  }));
});

非常感谢您的帮助

相关问题