
在前端开发中,我们经常需要处理日期和时间数据。一个常见的需求是,给定一个日期范围,将其中的所有日期按月份进行分组,并以结构化的数组形式呈现。例如,从5月1日到6月3日,我们希望得到一个包含5月份所有日期和6月份所有日期的嵌套数组。本教程将展示如何利用javascript的原生功能实现这一目标,无需引入额外的日期处理库。
我们将通过以下步骤实现目标:
为了使输出更具可读性,我们需要对日期进行格式化,特别是将日期数字转换为带有序数词后缀的形式(如“1st”、“2nd”)。JavaScript的Intl对象提供了强大的国际化功能,非常适合此任务。
Intl.DateTimeFormat可以帮助我们以本地化的方式获取月份名称。
const monthFrmt = new Intl.DateTimeFormat('en', { month: 'long' });
// 'en' 表示英文,'month: 'long'' 表示输出完整的月份名称,如 'May'生成序数词后缀(st, nd, rd, th)需要一些逻辑判断。Intl.PluralRules API可以帮助我们根据数字的复数规则选择正确的后缀。
立即学习“Java免费学习笔记(深入)”;
const rules = new Intl.PluralRules('en', { type: 'ordinal' });
const suffixes = { one: 'st', two: 'nd', few: 'rd', other: 'th' };
/**
* 根据数字生成带有序数词后缀的字符串
* @param {number} number - 日期数字
* @returns {string} - 带有序数词后缀的日期字符串
*/
const ordinal = (number) => {
const rule = rules.select(number);
return `${number}${suffixes[rule]}`;
};这个ordinal函数会根据传入的数字,如1、2、3、4等,返回“1st”、“2nd”、“3rd”、“4th”等字符串。
结合月份格式化器和序数词生成函数,我们可以创建一个统一的日期格式化函数,用于生成每个日期的显示文本。
/**
* 格式化日期为“序数日 月份名称”的字符串
* @param {Date} date - 要格式化的日期对象
* @returns {string} - 格式化后的日期字符串,如“1st May”
*/
const dateFormatterFn = (date) => `${ordinal(date.getDate())} ${monthFrmt.format(date)}`;现在,我们来构建主函数,它将遍历指定日期范围内的每一天,并将它们按月份分组。
这个函数接收起始日期、结束日期和日期格式化函数作为参数,返回一个按月份分组的日期数组。
/**
* 在指定日期范围内生成按月份分组的日期数组
* @param {Date} startDate - 日期范围的起始日期(包含)
* @param {Date} endDate - 日期范围的结束日期(包含)
* @param {Function} dateFormatterFn - 用于格式化单个日期的函数
* @returns {Array<Array<string>>} - 包含月份名称和其对应日期的嵌套数组
*/
const generateDates = (startDate, endDate, dateFormatterFn) => {
const results = []; // 存储最终结果的中间结构
const currDate = new Date(startDate.getTime()); // 使用副本,避免修改原始startDate
while (currDate <= endDate) {
const monthKey = monthFrmt.format(currDate); // 获取当前日期的月份名称
// 检查是否需要创建新的月份组
// 如果results为空,或者当前月份与上一个月份不同,则创建新的组
if (results.length === 0 || results[results.length - 1]?.key !== monthKey) {
results.push({ key: monthKey, values: [] });
}
// 将当前格式化的日期添加到当前月份组的values数组中
results[results.length - 1].values.push(dateFormatterFn(currDate));
// 移动到下一天
currDate.setDate(currDate.getDate() + 1);
}
// 将中间结构转换为最终所需的数组格式
// 例如:[{ key: "May", values: ["1st May", ...] }] 转换为 [["May", "1st May", ...]]
return results.map(Object.values);
};将所有部分整合在一起,形成一个完整的可运行示例。
const
// 月份名称格式化器,输出如 "May"
monthFrmt = new Intl.DateTimeFormat('en', { month: 'long' }),
// 定义日期范围
startDate = new Date('2023-05-01T00:00:00'), // 2023年5月1日
endDate = new Date('2023-06-03T00:00:00'); // 2023年6月3日 (包含)
// 序数词规则和后缀
const rules = new Intl.PluralRules('en', { type: 'ordinal' });
const suffixes = { one: 'st', two: 'nd', few: 'rd', other: 'th' };
/**
* 根据数字生成带有序数词后缀的字符串
* @param {number} number - 日期数字
* @returns {string} - 带有序数词后缀的日期字符串
*/
const ordinal = (number) => {
const rule = rules.select(number);
return `${number}${suffixes[rule]}`;
};
/**
* 格式化日期为“序数日 月份名称”的字符串
* @param {Date} date - 要格式化的日期对象
* @returns {string} - 格式化后的日期字符串,如“1st May”
*/
const dateFormatterFn = (date) => `${ordinal(date.getDate())} ${monthFrmt.format(date)}`;
/**
* 在指定日期范围内生成按月份分组的日期数组
* @param {Date} startDate - 日期范围的起始日期(包含)
* @param {Date} endDate - 日期范围的结束日期(包含)
* @param {Function} dateFormatterFn - 用于格式化单个日期的函数
* @returns {Array<Array<string>>} - 包含月份名称和其对应日期的嵌套数组
*/
const generateDates = (startDate, endDate, dateFormatterFn) => {
const results = [];
const currDate = new Date(startDate.getTime()); // 创建日期的副本进行操作
while (currDate <= endDate) {
const monthKey = monthFrmt.format(currDate);
// 如果是新月份,则创建一个新的组
if (results.length === 0 || results[results.length - 1]?.key !== monthKey) {
results.push({ key: monthKey, values: [] });
}
// 将格式化后的日期添加到当前月份组
results[results.length - 1].values.push(dateFormatterFn(currDate));
// 移动到下一天
currDate.setDate(currDate.getDate() + 1);
}
// 最终转换:将 { key: "Month", values: [...] } 结构转换为 ["Month", ...] 数组
return results.map(Object.values);
};
// 主执行函数
const main = () => {
const dates = generateDates(startDate, endDate, dateFormatterFn);
console.log(dates);
};
main();运行上述代码,将得到类似以下的输出结构:
[ ["May", "1st May", "2nd May", ..., "31st May"], ["June", "1st June", "2nd June", "3rd June"] ]
这种结构清晰地将每个月份的名称作为内部数组的第一个元素,后面跟着该月份内的所有日期。
通过本教程,我们学习了如何利用JavaScript的Intl.DateTimeFormat和Intl.PluralRules API,结合简单的循环逻辑,高效地生成一个按月份分组的日期范围数组。这种方法不仅功能强大、灵活,而且避免了对外部库的依赖,是处理日期分组需求的一个优雅且高性能的解决方案。
以上就是JavaScript中按月份分组生成日期范围数组的教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号