
本文将介绍如何使用原生 JavaScript 生成一个包含指定日期范围内所有日期的数组,并按月份进行分组。无需任何第三方库,即可实现类似 [May - month name, [1st May, 2nd May, 3rd May, ...], June, [1st June, 2nd June, 3rd June]] 这样的数据结构。文章将提供完整的代码示例,并解释关键步骤,帮助读者理解和应用。
使用原生 JavaScript 生成按月分组的日期数组
在 JavaScript 中,使用 Intl 对象可以方便地格式化日期和数字,而无需依赖 MomentJS 等第三方库。以下代码示例展示了如何生成指定日期范围内按月份分组的日期数组。
代码示例:
const
monthFrmt = new Intl.DateTimeFormat('en', { month: 'long' }),
startDate = new Date('2023-05-01T00:00:00'), // May 1st
endDate = new Date('2023-06-03T00:00:00'), // June 3rd (inclusive)
dateFormatterFn = (date) => `${ordinal(date.getDate())} ${monthFrmt.format(date)}`;
const main = () => {
const dates = generateDates(startDate, endDate, dateFormatterFn);
console.log(dates);
};
const generateDates = (startDate, endDate, dateFormatterFn) => {
const results = [], currDate = new Date(startDate.getTime());
while (currDate <= endDate) {
const key = monthFrmt.format(currDate);
if (results[results.length - 1]?.key !== key) results.push({ key, values: [] });
results[results.length - 1].values.push(dateFormatterFn(currDate));
currDate.setDate(currDate.getDate() + 1);
}
return results.map(Object.values);
}
const rules = new Intl.PluralRules('en', { type: 'ordinal' });
const suffixes = { one: 'st', two: 'nd', few: 'rd', other: 'th' };
const ordinal = (number) => `${number}${suffixes[rules.select(number)]}`;
main();代码解释:
- Intl.DateTimeFormat: new Intl.DateTimeFormat('en', { month: 'long' }) 创建了一个日期格式化对象,用于以英文格式获取月份的完整名称(例如,"May"、"June")。
- startDate 和 endDate: 定义了日期范围的起始和结束日期。
- dateFormatterFn: 这是一个函数,用于格式化日期。它使用 ordinal 函数获取日期的序数形式(例如,1st, 2nd, 3rd),并将其与月份名称组合。
-
generateDates: 这个函数是核心逻辑所在。它接受起始日期、结束日期和日期格式化函数作为参数,并返回按月份分组的日期数组。
- 它使用 while 循环遍历日期范围内的每一天。
- 对于每一天,它使用 monthFrmt.format(currDate) 获取月份名称。
- 如果当前月份与上一个月份不同,则创建一个新的月份条目。
- 然后,将格式化后的日期添加到当前月份的 values 数组中。
- ordinal: 这个函数用于获取数字的序数形式(1st, 2nd, 3rd, 等等)。它使用 Intl.PluralRules 来确定正确的后缀。
注意事项:
- endDate 包含在结果中。
- 代码使用了 Intl API,因此在不同的浏览器和环境中,日期格式可能会略有不同。
- 你可以根据需要修改 dateFormatterFn 函数,以自定义日期的格式。
总结:
通过使用原生 JavaScript 的 Intl 对象,可以方便地生成按月份分组的日期数组,而无需依赖第三方库。这种方法简洁高效,并且易于理解和修改。这个教程提供了一个清晰的示例,可以帮助开发者在各种 JavaScript 项目中处理日期和时间数据。










