本教程详细介绍了如何使用纯JavaScript,结合Intl.dateTimeFormat和Intl.PluralRules API,高效地在一个指定日期范围内生成一个按月份嵌套日期对象的数组。文章通过代码示例和详细解释,展示了如何实现日期分组和序数日期格式化,避免了对外部库的依赖。
在前端开发中,我们经常需要处理日期和时间数据。一个常见的需求是,给定一个日期范围,将其中的所有日期按月份进行分组,并以结构化的数组形式呈现。例如,从5月1日到6月3日,我们希望得到一个包含5月份所有日期和6月份所有日期的嵌套数组。本教程将展示如何利用javascript的原生功能实现这一目标,无需引入额外的日期处理库。
核心功能概述
我们将通过以下步骤实现目标:
- 定义日期范围的起始和结束日期。
- 使用Intl.DateTimeFormat API来格式化月份名称。
- 创建一个辅助函数来生成日期中的序数词(例如:1st, 2nd, 3rd)。
- 遍历日期范围内的每一天,将其按月份分组并存储。
准备工作:日期格式化与序数词生成
为了使输出更具可读性,我们需要对日期进行格式化,特别是将日期数字转换为带有序数词后缀的形式(如“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)}`;
核心逻辑实现:按月份分组日期
现在,我们来构建主函数,它将遍历指定日期范围内的每一天,并将它们按月份分组。
generateDates 函数
这个函数接收起始日期、结束日期和日期格式化函数作为参数,返回一个按月份分组的日期数组。
/** * 在指定日期范围内生成按月份分组的日期数组 * @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"] ]
这种结构清晰地将每个月份的名称作为内部数组的第一个元素,后面跟着该月份内的所有日期。
注意事项与扩展
- 本地化(Locale)支持:Intl.DateTimeFormat和Intl.PluralRules都支持传入不同的locale参数,例如’zh-CN’用于中文,’fr’用于法语。这使得生成的日期和月份名称能够适应不同的语言环境。
- 日期对象与字符串:本教程的示例输出的是格式化后的日期字符串。如果需要保留原始的Date对象或者其他自定义的数据结构,可以在results[results.length – 1].values.push()这一步中进行调整。
- 性能考量:对于非常大的日期范围(例如跨越数十年),循环的次数会相应增加。但在大多数常见应用场景中,这种纯JavaScript的实现方式性能是足够的。
- 替代方案:虽然本教程强调纯JavaScript的实现,但在某些大型项目中,如果已经引入了Moment.js、date-fns等日期处理库,也可以利用它们提供的API来简化日期遍历和格式化逻辑。然而,对于这种特定需求,原生Intl API提供了足够强大的功能且无需额外依赖。
总结
通过本教程,我们学习了如何利用JavaScript的Intl.DateTimeFormat和Intl.PluralRules API,结合简单的循环逻辑,高效地生成一个按月份分组的日期范围数组。这种方法不仅功能强大、灵活,而且避免了对外部库的依赖,是处理日期分组需求的一个优雅且高性能的解决方案。
评论(已关闭)
评论已关闭