如何从Javascript中的静态日期数组创建日期间隔数组?

时间:2014-12-19 00:23:52

标签: javascript date

从数组:

["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 }]; 

是否有可用于此类功能的库?

编辑更多信息:我想将第一个静态日期数组转换为表示时间间隔的对象数组。

1 个答案:

答案 0 :(得分: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;