MomentJS - Examples
Modern Date/Time: Moment.js Examples
Section titled “Modern Date/Time: Moment.js Examples”This section provides practical examples applying various Moment.js concepts. Remember the context: Moment.js is in maintenance mode, so these are primarily for understanding or maintaining existing code.
Example 1: Generating Dates within a Range
Section titled “Example 1: Generating Dates within a Range”This example generates an array of formatted date strings between a start and end date.
// Function to generate dates (inclusive)function getDateRange(startDate, endDate) { const start = moment(startDate); const end = moment(endDate); const dateArray = []; let current = start.clone(); // Use clone to avoid modifying the original start date
while (current.isSameOrBefore(end, 'day')) { dateArray.push(current.format('dddd, MMMM Do YYYY')); current.add(1, 'day'); }
return dateArray;}
// Usageconst 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*/This uses isSameOrBefore for the loop condition, clone to prevent mutation, add for iteration, and format for the output.
Example 2: Finding Specific Weekdays in a Range
Section titled “Example 2: Finding Specific Weekdays in a Range”This example finds all Sundays between two dates.
// Function to find specific weekdays (0=Sun, 1=Mon,... 6=Sat)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;}
// Usage: Find Sundays (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*/This builds on the previous example, adding a check using day() within the loop.
Example 3: Displaying Dates in Different Locales
Section titled “Example 3: Displaying Dates in Different Locales”This example shows how to display the same date/time in various formats according to different locales. (Assumes locales are loaded).
// Make sure locales are loaded first!// import 'moment/locale/fr';// import 'moment/locale/es';// import 'moment/locale/ja';
const now = moment();const localesToTest = ['en', 'fr', 'es', 'ja']; // English, French, Spanish, Japanese
localesToTest.forEach(locale => { console.log(`\n--- Locale: ${locale} ---`); moment.locale(locale); // Set global locale temporarily for these examples
console.log(`Default Format: ${now.format()}`); // Default ISO format (not locale-specific) 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(', ')}`);});
// Reset locale if neededmoment.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月*/This demonstrates the power of locale() combined with locale-aware formatting methods like format('LLLL'), calendar(), and fromNow(), as well as accessing locale data like monthsShort().