嗨,我的问题有点特别,或许不是。然而,问题是我解析了一个数组中的日期范围,我需要找到起始日期和结束日期,以便在范围内发生。我不知道我是否解释得很好,但如果您需要更多信息,请告诉我。在多个日期范围内的开始日期和结束日期范围
例如[2010-7-11,2010-7-12,2010-7-13,2010年9月1日,2010年9月2日,....]
现在
2010年7月11日开始和结束2010-7-13
2010年9月1日开始2010年9月2日结束
所以对阵列中的整个范围
在此先感谢
嗨,我的问题有点特别,或许不是。然而,问题是我解析了一个数组中的日期范围,我需要找到起始日期和结束日期,以便在范围内发生。我不知道我是否解释得很好,但如果您需要更多信息,请告诉我。在多个日期范围内的开始日期和结束日期范围
例如[2010-7-11,2010-7-12,2010-7-13,2010年9月1日,2010年9月2日,....]
现在
2010年7月11日开始和结束2010-7-13
2010年9月1日开始2010年9月2日结束
所以对阵列中的整个范围
在此先感谢
这里的东西快速脏。它预计dates
数组已经按升序排序。
var dates = ["2010-7-11", "2010-7-12", "2010-7-13", "2010-9-01", "2010-9-02"],
startDates = [], endDates = [],
lastDate = null, date = null;
for (var i=0, l=dates.length; i<l; ++i) {
date = new Date(dates[i].replace(/-/g, "/"));
//
if (!lastDate) {
startDates.push(lastDate = date);
}
// If the diffrence between the days is greater than the number
// of milliseconds in a day, then it is not consecutive
else if (date - lastDate > 86400000) {
lastDate = null;
endDates.push(date);
}
}
// Close the last range
endDates.push(date);
// Result is two symetical arrays
console.log(startDates, endDates);
这不起作用,例如,如果我们在数组中有3个以上的元素,无论日期是否被排序,4元素也被指定为开始日期,即使它是连续的一部分...但是无论如何, – Narayan 2010-02-15 17:21:32
“范围”你的意思是“连续几天”? – 2010-02-11 11:53:21
是的,这是正确的 – Narayan 2010-02-11 11:56:09
以及范围我的意思是,但内部数组可能有多个范围等我需要描述每个范围的开始和结束。 – Narayan 2010-02-11 11:57:27