2014-12-19 17 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; 
相关问题