使用node.js获取2个日期之间的日期

时间:2016-07-15 05:57:56

标签: javascript node.js date

node.js中,我需要在特定差距的日期范围内获取日期。

考虑两个日期:

startDate:2016-07-10T00:00:00.000Z,
payByDate:"13"(13th of every month);
endDate:2016-10-08T00:00:00.000Z

我需要这两个日期之间每月或每周差距的日期数组。

我的结果应该是:(每月差距)

[2016-07-13T00:00:00.000Z,
 2016-08-13T00:00:00.000Z,
 2016-09-13T00:00:00.000Z]

修改  我的开始日期是2016-07-10T00:00:00.000Z,所以我可以使用endDate-startdate计算noOfmonths,但数组条目应该是payByDate

我正在使用MOMENT.JS,但它只返回noOfMonths而不是日期。请分享您的想法。提前谢谢。

现在可以计算出Above数组的计算结果。请注意" payByDate"是字符串。

2 个答案:

答案 0 :(得分:0)

尝试使用manipulate method in moment.js将一个月添加到开始日期,直到您到达第二个日期。

考虑这段代码。假设第一个日期和最后一个日期已经传递到此函数的时刻,您可以使用diff和manipulate方法在两个不同日期之间按月创建日期数组:

修改

function monthsBetween(payByDate, startDate, lastDate) {
  var months = [];

  //finds nearest date to the start date that is on the payByDate
  var currentDate = startDate.date(parseInt(payByDate));

  //checks if the date is after the startDate and adds a month if it is
  if(!currentDate.isSameOrAfter(startDate)){
    currentDate = currentDate.add(1, 'months');
  }

  while (currentDate.isSameOrBefore(lastDate)) {
    months.push(currentDate);
    currentDate = currentDate.add(1, 'months');
  }

  return months;
}

答案 1 :(得分:0)

您可以使用getMonth()功能获取约会的月份。然后继续添加一个,直到你到达结束日期。

var arrayDates = [];
arrayDates.push(startDate);
var tempDate = new Date(new Date(startDate).setMonth(startDate.getMonth()+1));
while(tempDate < endDate)
{
   arrayDates.push(tempDate);
   var tempDate = new Date(new Date(tempDate).setMonth(tempDate.getMonth()+1));
}

Abouve逻辑将适用于月度差距。要获得每周差距数组,请使用getDate()函数并继续向其添加7直到达到结束日期