本文介绍如何基于 javascript 快速统计一组 iso 格式日期字符串中包含的总天数、周末(周六/周日)出现次数,以及作为每月首日的日期数量,并输出结构化结果对象。
在处理时间序列数据(如日志记录、用户活跃度、排期表等)时,常需从日期列表中提取基础统计维度:总天数、周末天数(即星期六或星期日)、以及跨月次数(通常以每月 1 号为标识)。本文提供三种渐进式实现方案——从清晰易读的 forEach 循环,到函数式风格的 filter 链式调用,再到高度简洁的箭头函数写法,兼顾可维护性与开发效率。
⚠️ 注意:getDay() 返回的是星期几(0=周日,1=周一…6=周六),而 getDate() 返回的是当月第几天(1~31),二者不可混淆。
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 = dateList.length;
let weekendCount = 0;
let monthCount = 0;
dateList.forEach(dateStr => {
const date = new Date(dateStr);
if (date.getDay() === 0 || date.getDay() === 6) weekendCount++;
if (date.getDate() === 1) monthCount++;
});
const result = { day: dayCount, weekend: weekendCount, month: monthCount };
console.log(result); // { day: 4, weekend: 1, month: 1 }利用 filter() 提升语义表达力,避免手动维护计数器:
const dateList = [/* 同上 */];
const result = {
day: dateList.length,
weekend: dateList.filter(str => {
const d = new Date(str);
return d.getDay() === 0 || d.getDay() === 6;
}).length,
month: dateList.filter(str => new Date(str).getDate() === 1).length
};
console.log(result);借助取模技巧简化周末判断(getDay() % 6 === 0 等价于 0 或 6),进一步压缩代码:
const dateList = [/* 同上 */];
const result = {
day: dateList.length,
weekend: dateList.filter(str => new Date(str).getDay() % 6 === 0).length,
month: dateList.filter(str => new Date(str).getDate() === 1).length
};const months = new Set(dateList.map(d => new Date(d).toISOString().slice(0, 7))); monthCount = months.size;
最终,无论采用哪种写法,均可轻松封装为复用函数:
const analyzeDates = (dates) => ({
da
y: dates.length,
weekend: dates.filter(d => new Date(d).getDay() % 6 === 0).length,
month: dates.filter(d => new Date(d).getDate() === 1).length
});即刻集成,高效解析你的日期数据流。