
本文将介绍如何使用原生 JavaScript 生成一个包含指定日期范围内所有日期的数组,并按月份进行分组。无需任何第三方库,即可实现类似 [May - month name, [1st May, 2nd May, 3rd May, ...], June, [1st June, 2nd June, 3rd June]] 这样的数据结构。文章将提供完整的代码示例,并解释关键步骤,帮助读者理解和应用。
在 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();代码解释:
注意事项:
总结:
通过使用原生 JavaScript 的 Intl 对象,可以方便地生成按月份分组的日期数组,而无需依赖第三方库。这种方法简洁高效,并且易于理解和修改。这个教程提供了一个清晰的示例,可以帮助开发者在各种 JavaScript 项目中处理日期和时间数据。
以上就是生成指定日期范围内按月分组的日期数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号