2017-04-18 197 views
-4

我正在尋找解決方案,但我沒有得到我除了。我如何獲得開始日期和結束日期之間的月和年

案例:開始日期:10/17/2017和結束日期:02/23/2018 從我想幾個月甚至幾年的陣列格式像下面

 array 1 
     - 2017 
     -10 
     -11 
     -12 
     array 2 
     - 2018 
     -01 
     -02 

請讓我知道你的建議,這些日期範圍。提前致謝。

+3

歡迎SO。請訪問[幫助],看看有什麼和如何問。建議:發佈工作量和代碼,但在修復拼寫錯誤後,首先在Google中搜索您的標題:https://www.google.com/search?q=array+of+months+and+years+between+start+date+and+結束+日期+ javascript – mplungjan

+0

爲什麼你不使用Date對象來存儲日期?你可以使用JS庫來做一些符合你的描述的東西 - http://stackoverflow.com/a/21293157/2344348。 –

+1

重複的http://stackoverflow.com/a/21293157/2344348 –

回答

1

我很好奇,所以我寫了它 - 不妨發佈它。 Moment.js在這裏是巨大的矯枉過正。

var obj = {}, start=new Date("10/17/2017"), end=new Date("02/23/2018"); 
 
for (var i=start.getTime(), n = end.getTime(); i<=n;) { // we update i later 
 
    var d=new Date(i), year = d.getFullYear(), month=d.getMonth()+1; 
 
    if (!obj[year]) obj[year] = [month]; // initialise array 
 
    else obj[year].push(month); // add to array 
 
    d.setMonth(month); // next month 
 
    i = d.getTime(); // here instead of in the for statement 
 
} 
 
console.log(obj);

相關問題