2016-09-20 195 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

相關問題