
本文介绍如何使用原生 JavaScript 生成指定日期范围内,按月份分组的日期数组。无需依赖第三方库,利用 Intl 对象格式化日期,并提供完整的代码示例,帮助开发者轻松实现日期数据的结构化处理。
在 JavaScript 中,处理日期和时间可能比较繁琐。本文将介绍一种使用原生 JavaScript(无需 MomentJS 或其他日期库)生成日期范围内按月分组的日期数组的方法。这种方法利用 Intl 对象进行本地化日期格式化,提供了一种简洁高效的解决方案。
Intl 对象是 ECMAScript 国际化 API 的一部分,它提供了日期、时间、数字和货币格式化的功能。通过 Intl.DateTimeFormat,我们可以根据指定的 locale(例如 'en' 表示英语)格式化日期。
const monthFrmt = new Intl.DateTimeFormat('en', { month: 'long' });
const formattedMonth = monthFrmt.format(new Date()); // 例如: "July"以下代码展示了如何生成指定日期范围内按月分组的日期数组:
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();代码解释:
输出结果示例:
对于 startDate = '2023-05-01' 和 endDate = '2023-06-03',输出结果如下:
[ [ 'May', [ '1st May', '2nd May', '3rd May', '4th May', '5th May', '6th May', '7th May', '8th May', '9th May', '10th May', '11th May', '12th May', '13th May', '14th May', '15th May', '16th May', '17th May', '18th May', '19th May', '20th May', '21st May', '22nd May', '23rd May', '24th May', '25th May', '26th May', '27th May', '28th May', '29th May', '30th May', '31st May' ] ], [ 'June', [ '1st June', '2nd June', '3rd June' ] ] ]
本文提供了一种使用原生 JavaScript 生成日期范围内按月分组的日期数组的方法。通过利用 Intl 对象进行日期格式化,避免了对第三方日期库的依赖,使代码更加简洁高效。这种方法可以灵活地应用于各种需要处理日期数据的场景。
以上就是生成日期范围内按月分组的日期数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号