Skip to content

MomentJS - 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;
}
// Usage
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 2024
Monday, March 11th 2024
Tuesday, March 12th 2024
Wednesday, March 13th 2024
Thursday, March 14th 2024
Friday, 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 2024
Sunday, April 14th 2024
Sunday, April 21st 2024
Sunday, 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 needed
moment.locale('en');
/* Example Console Output Snippets:
--- Locale: en ---
Default Format: 2023-10-26T16:15:00+01:00
LLLL Format: Thursday, October 26, 2023 4:15 PM
Calendar Time: Today at 4:15 PM
Relative Time: 2 hours ago
Months: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
--- Locale: fr ---
Default Format: 2023-10-26T16:15:00+01:00
LLLL Format: jeudi 26 octobre 2023 16:15
Calendar Time: Aujourd’hui à 16:15
Relative Time: il y a 2 heures
Months: 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:00
LLLL Format: jueves, 26 de octubre de 2023 16:15
Calendar Time: Hoy a las 16:15
Relative Time: hace 2 horas
Months: ene, feb, mar, abr, may, jun, jul, ago, sep, oct, nov, dic
--- Locale: ja ---
Default Format: 2023-10-26T16:15:00+01:00
LLLL 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().