MomentJS - 示例
现代日期/时间处理:Moment.js 示例
Section titled “现代日期/时间处理:Moment.js 示例”本节提供应用各种 Moment.js 概念的实际示例。请记住背景信息:Moment.js 处于维护模式,因此这些示例主要用于理解或维护现有代码。
示例 1:生成一个日期范围内的日期
Section titled “示例 1:生成一个日期范围内的日期”此示例生成一个起始日期和结束日期之间的格式化日期字符串数组。
// 生成日期(包含起始/结束日期)的函数function getDateRange(startDate, endDate) { const start = moment(startDate); const end = moment(endDate); const dateArray = []; let current = start.clone(); // 使用 clone 避免修改原始起始日期
while (current.isSameOrBefore(end, 'day')) { dateArray.push(current.format('dddd, MMMM Do YYYY')); current.add(1, 'day'); }
return dateArray;}
// 使用示例const startDate = '2024-03-10';const endDate = '2024-03-15';const datesInRange = getDateRange(startDate, endDate);
console.log(`Dates between ${startDate} and ${endDate}:`);datesInRange.forEach(date => console.log(date));
/* Expected Console Output:Dates between 2024-03-10 and 2024-03-15:Sunday, March 10th 2024Monday, March 11th 2024Tuesday, March 12th 2024Wednesday, March 13th 2024Thursday, March 14th 2024Friday, March 15th 2024*/这里使用了 isSameOrBefore 作为循环条件,clone 来防止 mutation(变动),add 用于迭代,format 用于输出格式。
示例 2:在一个日期范围中查找特定星期几
Section titled “示例 2:在一个日期范围中查找特定星期几”此示例查找两个日期之间的所有周日。
// 查找特定星期几的函数 (0=周日, 1=周一,... 6=周六)function findWeekdaysInRange(startDate, endDate, dayOfWeek) { const start = moment(startDate); const end = moment(endDate); const dateArray = []; let current = start.clone();
while (current.isSameOrBefore(end, 'day')) { if (current.day() === dayOfWeek) { dateArray.push(current.format('dddd, MMMM Do YYYY')); } current.add(1, 'day'); }
return dateArray;}
// 使用示例:查找周日 (dayOfWeek = 0)const rangeStart = '2024-04-01';const rangeEnd = '2024-04-30';const sundays = findWeekdaysInRange(rangeStart, rangeEnd, 0);
console.log(`Sundays between ${rangeStart} and ${rangeEnd}:`);sundays.forEach(date => console.log(date));
/* Expected Console Output:Sundays between 2024-04-01 and 2024-04-30:Sunday, April 7th 2024Sunday, April 14th 2024Sunday, April 21st 2024Sunday, April 28th 2024*/这以上一个示例为基础,在循环内增加了使用 day() 进行检查。
示例 3:在不同的 Locale 中显示日期
Section titled “示例 3:在不同的 Locale 中显示日期”此示例展示如何根据不同的 locale 以各种格式显示同一日期/时间。(假设已加载 locale 数据)。
// 请确保首先加载了 locales!// import 'moment/locale/fr';// import 'moment/locale/es';// import 'moment/locale/ja';
const now = moment();const localesToTest = ['en', 'fr', 'es', 'ja']; // 英语、法语、西班牙语、日语
localesToTest.forEach(locale => { console.log(`\n--- Locale: ${locale} ---`); moment.locale(locale); // 临时设置全局 locale 用于这些示例
console.log(`Default Format: ${now.format()}`); // 默认的 ISO 格式(与 locale 无关) console.log(`LLLL Format: ${now.format('LLLL')}`); console.log(`Calendar Time: ${now.calendar()}`); console.log(`Relative Time: ${moment().subtract(2, 'hours').fromNow()}`); console.log(`Months: ${moment.monthsShort().join(', ')}`);});
// 如有需要,重置 localemoment.locale('en');
/* Example Console Output Snippets:
--- Locale: en ---Default Format: 2023-10-26T16:15:00+01:00LLLL Format: Thursday, October 26, 2023 4:15 PMCalendar Time: Today at 4:15 PMRelative Time: 2 hours agoMonths: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
--- Locale: fr ---Default Format: 2023-10-26T16:15:00+01:00LLLL Format: jeudi 26 octobre 2023 16:15Calendar Time: Aujourd’hui à 16:15Relative Time: il y a 2 heuresMonths: janv., févr., mars, avr., mai, juin, juil., août, sept., oct., nov., déc.
--- Locale: es ---Default Format: 2023-10-26T16:15:00+01:00LLLL Format: jueves, 26 de octubre de 2023 16:15Calendar Time: Hoy a las 16:15Relative Time: hace 2 horasMonths: ene, feb, mar, abr, may, jun, jul, ago, sep, oct, nov, dic
--- Locale: ja ---Default Format: 2023-10-26T16:15:00+01:00LLLL Format: 2023年10月26日木曜日 16時15分Calendar Time: 今日の16時15分Relative Time: 2時間前Months: 1月, 2月, 3月, 4月, 5月, 6月, 7月, 8月, 9月, 10月, 11月, 12月*/这展示了 locale() 方法结合 format('LLLL')、calendar() 和 fromNow() 等 locale 感知格式化方法,以及访问 monthsShort() 等 locale 数据的强大功能。