2016-09-20 51 views
1

我有一个开始日期(星期日)和结束日期(星期六),我想要创建一个包含它们之间所有星期日的数组。使用momentjs/lodash,我如何在两个日期之间添加日/星期?

这是我到目前为止有:

weeks = [{ 
     start: startDate, 
     end: angular.copy(startDate).add(6, 'days') 
    }]; 

    while(_.last(weeks).end <= endDate) { 
     weeks.push({ 
     start: angular.copy(_.last(weeks)).start.add(7, 'days'), 
     end: angular.copy(_.last(weeks)).end.add(7, 'days') 
     }) 
    } 

这种感觉很凌乱,也,它在某种程度上是错误的。它只会增加一天,因此会增加多天。我不特别关心日期,但如果我能得到它,我会接受它。

回答

2

以下是建立在while循环上的简单解决方案。在这种情况下,我认为lodash语法只会使问题复杂化。

从第一个星期日开始,并重复添加7天,直到您通过星期六结束。将时刻对象的克隆推入数组中。如果您不克隆,则最后会列出相同的日期,因为您继续引用单个时刻对象,在此情况下为start

var start = moment('2016-09-18'); //last sunday 
var finish = moment('2016-10-29'); //saturday in october 

// an array of moment objects 
var sundays = [start.clone()]; // include the first sunday 

// foreach additional sunday, clone it into an array 
while(start.add(7, 'days').isBefore(finish)) { 
    sundays.push(start.clone()); 
} 
+0

是'.clone'的一瞬间吗? – Shamoon

+0

是的,'.clone'是时刻对象的函数。为了参考,在这里它是在源 - https://github.com/moment/moment/blob/e90e864617d3c501c2eaa1119392781c58a2ce63/moment.js#L2953-L2955 – ThisClark

相关问题