使用linq.js和momentjs创建2个日期的日期范围

时间:2015-03-26 22:11:14

标签: javascript momentjs linq.js

我想获取startDate和endDate之间的所有日期。

我再次使用moment()包装startDate / endDate来克隆start / endDate,因为它们不能被更改。

但是getDateRange仍然给出了关于日期的奇怪结果:

 testCase.startDate = moment(new Date(2014, 0, 1));
 testCase.endDate = moment(new Date(2014, 0, 27));

虽然这两个日期都是2014年,但我从2013年12月开始获得dateRange?

为什么?

 function getDateRange(startDate, endDate) {
    return Enumerable.range(0, moment(endDate).diff(moment(startDate), 'days') + 1)
      .select(function (offset) {
        return moment(startDate).add(offset, 'days')
      })
      .toArray();
  }

更新

enter image description here

1 个答案:

答案 0 :(得分:0)

您的查询看起来应该有效。也许你不正确地解释日期。请记住,只有月份从0开始。也许你在查看价值时也会抵消这一年。

以下是您可以编写查询的另一种方法:

function getDateRange(startDate, endDate) {
    return Enumerable.Unfold(startDate, "moment($).add(1, 'd')")
        .TakeWhile(function (d) { return d <= endDate; })
        .ToArray();
}

根据我在评论中看到的内容,您似乎正在使用改变日期的方法。您要么想避免使用这些方法,要么首先克隆日期并操纵克隆。

// without cloning
var date1 = moment.utc([2014, 0, 1]);
console.log(String(date1)); // Wed Jan 01 2014 00:00:00 GMT+0000
var startOfDate1 = date1.startOf('week'); // mutated
console.log(String(date1)); // Sun Dec 29 2013 00:00:00 GMT+0000

// using moment()
var date2 = moment.utc([2014, 0, 1]);
console.log(String(date2)); // Wed Jan 01 2014 00:00:00 GMT+0000
var startOfDate2 = moment(date2).startOf('week'); // not mutated
console.log(String(date2)); // Wed Jan 01 2014 00:00:00 GMT+0000

// using clone()
var date3 = moment.utc([2014, 0, 1]);
console.log(String(date3)); // Wed Jan 01 2014 00:00:00 GMT+0000
var startOfDate3 = date3.clone().startOf('week'); // not mutated
console.log(String(date3)); // Wed Jan 01 2014 00:00:00 GMT+0000