
本文介绍如何基于 javascript 快速统计一组 iso 格式日期字符串中包含的总天数、周末(周六/周日)出现次数,以及作为每月首日的日期数量,并输出结构化结果对象。
在处理时间序列数据(如日志记录、用户活跃度、排期表等)时,常需从日期列表中提取基础统计维度:总天数、周末天数(即星期六或星期日)、以及跨月次数(通常以每月 1 号为标识)。本文提供三种渐进式实现方案——从清晰易读的 forEach 循环,到函数式风格的 filter 链式调用,再到高度简洁的箭头函数写法,兼顾可维护性与开发效率。
✅ 基础逻辑说明
- day:直接取数组长度(每个元素代表一个独立日期);
- weekend:判断 Date.getDay() 返回值是否为 0(周日)或 6(周六);
- month:判断 Date.getDate() 是否等于 1(即该日期是否为当月第 1 天)。
⚠️ 注意:getDay() 返回的是星期几(0=周日,1=周一…6=周六),而 getDate() 返回的是当月第几天(1~31),二者不可混淆。
? 方案一:清晰可读型(推荐初学者/生产环境)
const dateList = [
"2023-01-31T23:00:00.000Z",
"2023-02-01T23:00:00.000Z",
"2023-02-02T23:00:00.000Z",
"2023-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
};? 补充说明与注意事项
- 所有方案均默认输入为合法 ISO 8601 字符串(如 "2023-02-01T23:00:00.000Z"),若存在无效日期,建议预先校验:!isNaN(new Date(dateStr).getTime());
- 时区影响已由 new Date(...) 自动处理(UTC 解析),若需按本地时区统计,请确保原始数据或解析逻辑对齐业务时区;
- 若“月份数”实际指覆盖的不同月份总数(例如 ["2023-01-01", "2023-01-15", "2023-02-10"] → 2 个月),则应改用 Set 去重年月:
const months = new Set(dateList.map(d => new Date(d).toISOString().slice(0, 7))); monthCount = months.size;
最终,无论采用哪种写法,均可轻松封装为复用函数:
const analyzeDates = (dates) => ({
day: dates.length,
weekend: dates.filter(d => new Date(d).getDay() % 6 === 0).length,
month: dates.filter(d => new Date(d).getDate() === 1).length
});即刻集成,高效解析你的日期数据流。










