2014-12-19 39 views
0

從一個數組:如何從Javascript中的靜態日期數組中創建日期間隔數組?

["01/01/2015", "02/01/2015", "03/01/2015", "05/01/2015", "06/01/2015"]; 

[{begin_date: "01/01/2015", end_date: "03/01/2015"}, { begin_date: "05/05/2015", end_date: "06/01/2015 }]; 

是否有可用於該類型的函數庫?

編輯更多信息:我想將第一個靜態日期數組轉換爲表示時間間隔的對象數組。

+0

它看起來像你試圖建立一個JSON字符串正確嗎? – 2014-12-19 00:25:07

+0

是的。我認爲後臺的表格結構最好是格式爲start_date |結束日期。 – Trace 2014-12-19 00:26:14

+0

爲什麼downvotes?不是一個有效的編程問題?雖然看起來像一個有用的圖書館,但還沒有在Google上找到它...... – Trace 2014-12-19 00:28:11

回答

0

我使用Moment對象和下劃線。我結束了以下工作代碼:

 //Create arrays 
     var coll_dateIntervals = []; 
     var arr_temp = []; 
     _.each(collDates, function(moment_date, index, list){ 
      //Day difference in # of days 
      var diff = Math.abs(collDates[index].diff(collDates[index + 1], "days")); 

      //Add begin_date 
      arr_temp.push(moment_date); 
      //Check the date difference in days. 
      if(diff <= 1 && diff !== undefined){ 
       //If the difference is 1, than add the date to the temporary array 
       arr_temp.push(moment_date); 
       //If it's more than 1 day, or the last object 
      } else if (diff > 1 || diff === undefined){ 
       //Store the interval in an object 
       var obj_dateInterval = { start_date: arr_temp[0].format("DD/MM/YYYY"), end_date: arr_temp[arr_temp.length - 1].format("DD/MM/YYYY")}; 
       coll_dateIntervals.push(obj_dateInterval); 

       //Empty the array to start the new loop 
       arr_temp = []; 
      }; 
     }); 
     console.log(coll_dateIntervals); 

     //return coll_dateIntervals; 
相關問題