本文介绍如何基于 iso 格式日期字符串数组,高效统计总天数、周末天数(周六/周日)及出现的月份数(以每月1号为标识),提供三种递进优化的 javascript 实现方案,并附关键注意事项。
在处理时间序列分析、用户活跃度统计或日志聚合等场景时,常需从一组日期中快速提取基础时间维度指标:总天数(即日期条目数量)、周末天数(星期六或星期日)、以及涉及的月份数(注意:此处“months”指列表中有多少个日期是当月的第一天,即 date.getDate() === 1,而非去重后的月份数量——这是原需求明确的逻辑,下文将严格遵循)。
以下是三种清晰、可维护且逐步精简的实现方式:
使用显式计数器,逐项解析并判断,逻辑直观,便于调试和扩展。
const dateList = [
"2025-01-31T23:00:00.000Z",
"2025-02-01T23:00:00.000Z",
"2025-02-02T23:00:00.000Z",
"2025-02-03T23:00:00.000Z"
];
let dayCount = 0;
let weekendCount = 0;
let monthCount = 0;
dateList.forEach(dateStr => {
const date = new Date(dateStr);
dayCount++;
// 周末判断:getDay() 返回 0(周日)或 6(周六)
if (date.getDay() === 0 || date.getDay() === 6) {
weekendCount++;
}
// 月初判断:getDate() === 1 表示该日期是当月第1天
if (date.getDate() === 1) {
monthCount++;
}
});
console.log({
day: dayCount,
weekend: weekendCount,
month: monthCount
});
// 示例输出:{ day: 4, weekend: 1, month: 1 }避免手动维护变量,利用数组方法链提升可读性,适合中等规模数据。
const dateList = [/* 同上 */];
const dayCount = dateList.length;
const weekendCount = dateList.filter(str => {
const d = new Date(str);
return d.getDay() === 0 || d.getDay() === 6;
}).length;
const monthCount = dateList.filter(str => new
Date(str).getDate() === 1).length;
console.log({ day: dayCount, weekend: weekendCount, month: monthCount });结合箭头函数与 getDay() 的模运算小技巧(getDay() % 6 === 0 等价于 0 或 6),代码紧凑但需注意可读性权衡:
const dateList = [/* 同上 */];
const result = {
day: dateList.length,
weekend: dateList.filter(s => new Date(s).getDay() % 6 === 0).length,
month: dateList.filter(s => new Date(s).getDate() === 1).length
};
console.log(result);最终,你可将任意方案封装为复用函数:
const analyzeDates = (dates) => {
if (!Array.isArray(dates)) throw new Error('Input must be an array');
const validDates = dates.filter(d => d && !isNaN(new Date(d).getTime()));
return {
day: validDates.length,
weekend: validDates.filter(s => [0,6].includes(new Date(s).getDay())).length,
month: validDates.filter(s => new Date(s).getDate() === 1).length
};
};