gpt4 book ai didi

javascript - 在 JavaScript 中按周和月对日期 "yyyy-mm-dd"的简单数组进行分组

转载 作者:行者123 更新时间:2023-12-01 04:09:47 24 4
gpt4 key购买 nike

我想按周和月对一个简单的日期数组进行分组(在一个数组中)。我知道有很多例子,而且这个问题已经被问过很多次了,但我找不到一个非常简单的日期格式的例子,而不是日期时间戳。

我的日期数据数组如下所示:

"timeline_data": [
"2016-12-20",
"2016-12-21",
"2016-12-22",
"2016-12-23",
"2016-12-24",
"2016-12-25",
"2016-12-26",
"2016-12-27",
"2016-12-28",
"2016-12-29",
"2016-12-30",
"2016-12-31",
"2017-01-01",
"2017-01-02",
"2017-01-03",
"2017-01-04",
"2017-01-05",
"2017-01-06",
"2017-01-07",
"2017-01-08",
"2017-01-09",
"2017-01-10"
]

这就是让我困惑的原因:我不确定是否有一种简单的方法可以循环遍历这个数组,并简单地将项目插入新数组,或者日期是否必须是修改后,将“-”删除,如下所示:

var date="2016-12-20";
var newDate = date.replace(/-/g, "");

显然,“-”必须被替换。

希望有更简单的方法。

最佳答案

我会做类似以下的事情,希望评论足够。可能有一种更时髦的方法,但这种方法对我来说相当清楚:

/* Helper to get the ISO week number of a date
** @param {Date} date to get week of
** @returns {Array} [year, weekNumber]
*/
function getWeekNumber(d) {
d = new Date(+d);
d.setHours(0,0,0,0);
d.setDate(d.getDate() + 4 - (d.getDay()||7));
var yearStart = new Date(d.getFullYear(),0,1);
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
return [d.getFullYear(), weekNo];
}

/* Parse ISO 8601 format date string to local date
** @param {string} s - string to parse like 2016-12-15
** @returns {Date}
*/
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2]);
}

var data = [ "2016-12-20", "2016-12-21", "2016-12-22", "2016-12-23", "2016-12-24", "2016-12-25", "2016-12-26", "2016-12-27", "2016-12-28", "2016-12-29", "2016-12-30", "2016-12-31", "2017-01-01", "2017-01-02", "2017-01-03", "2017-01-04", "2017-01-05", "2017-01-06", "2017-01-07", "2017-01-08", "2017-01-09", "2017-01-10"];

// Prepend year and week number to dates, e.g. "201651:2016-12-20", then sort
var arr = data.map(function(s){
var week = getWeekNumber(parseISOLocal(s));
return week[0] + ('0' + week[1]).slice(-2) + ':' + s;
}).sort();

// Group in arrays by week in an object
var groupedObj = arr.reduce(function (result, value) {
var b = value.split(':');
if (!result[b[0]]) result[b[0]] = [];
result[b[0]].push(b[1]);
return result;
},{});

// Grab arrays in order of week number. Sort keys to maintain order
var groupedArray = Object.keys(groupedObj).sort().map(key=>groupedObj[key]);

// Final set of grouped dates
console.log(groupedArray.join('\n\n'))

getWeekNumber 函数借自 here .

关于javascript - 在 JavaScript 中按周和月对日期 "yyyy-mm-dd"的简单数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41584129/

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