gpt4 book ai didi

javascript - 如何从 jquery 或 javascript 中的静态日期数组中获取日期范围

转载 作者:行者123 更新时间:2023-12-03 05:07:44 26 4
gpt4 key购买 nike

我想从数组的静态日期创建日期范围。
这是我想要的示例:

var collDates = [
"2017/01/01",
"2017/01/02",
"2017/01/03",
"2017/01/04",
"2017/01/08",
"2017/01/09"
];

这应该转换为:

[
{ start_date: "2017/01/01", end_date: "2017/01/04" },
{ start_date: "2017/01/08", end_date: "2017/01/09" }
];

最佳答案

我已经解决了这个问题,这里是一个示例代码。

var staticDates = ["2017/01/01", "2017/01/02", "2017/01/03", "2017/01/04", "2017/01/08", "2017/01/09", "2017/01/10", "2017/01/11", "2017/01/12", "2017/01/13", "2017/01/14", "2017/01/15", "2017/01/16", "2017/01/17", "2017/01/18", "2017/01/19", "2017/01/20", "2017/01/21", "2017/01/22", "2017/01/23", "2017/01/24", "2017/01/25", "2017/01/26", "2017/01/27", "2017/01/28", "2017/01/29"];
var coll_dateIntervals = [];
var arr_temp = [];
var i = 1;
$.each(staticDates, function(index, moment_date){

//Day difference in # of days
var diff = Math.abs(moment(staticDates[index]).diff(staticDates[index + 1], "days"));

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
console.log(arr_temp[arr_temp.length - 1]);
var obj_dateInterval = { start_date: moment(arr_temp[0], "YYYY/MM/DD").format('YYYY-MM-DD'), end_date: moment(arr_temp[arr_temp.length - 1], "YYYY/MM/DD").format('YYYY-MM-DD')};
coll_dateIntervals.push(obj_dateInterval);

//Empty the array to start the new loop
arr_temp = [];

}

});
console.log(coll_dateIntervals);

关于javascript - 如何从 jquery 或 javascript 中的静态日期数组中获取日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41954736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com