Formatting Date And Time
Modern Date/Time: Formatting with Moment.js
Section titled “Modern Date/Time: Formatting with Moment.js”Displaying dates and times in specific, human-readable formats is a core requirement. Moment.js excels at this, offering flexible formatting options, relative time expressions, and various output types.
While powerful, remember Moment.js is in maintenance mode. For new projects, alternatives like Day.js, date-fns, or the native Intl.DateTimeFormat API might be more suitable, potentially offering better performance and tree-shaking.
Core Formatting Methods
Section titled “Core Formatting Methods”Here are the primary methods for formatting and displaying Moment objects:
| Method | Description & Example Syntax |
|---|---|
| Format | The most versatile method. Uses tokens (e.g., ‘YYYY-MM-DD’) to define the output string.moment().format(); // Default ISO 8601 formatmoment().format('MMMM Do YYYY, h:mm:ss a'); // e.g., October 26th 2023, 3:30:00 pmmoment().format('dddd'); // e.g., Thursday |
| Time from Now | Displays relative time from the current moment.moment().subtract(10, 'minutes').fromNow(); // '10 minutes ago'moment().add(2, 'hours').fromNow(); // 'in 2 hours'moment().add(2, 'hours').fromNow(true); // '2 hours' (without suffix) |
| Time from X | Displays relative time from a specific moment.const pastDate = moment('2023-01-01');moment().from(pastDate); // e.g., '10 months ago' |
| Time to Now | Similar to fromNow, but reversed logic (less common).moment().add(10, 'minutes').toNow(); // 'in 10 minutes' |
| Time to X | Similar to from, but reversed logic.const futureDate = moment('2024-01-01');moment().to(futureDate); // e.g., 'in 2 months' |
| Calendar Time | Displays time relative to a reference time (defaults to now) using locale-aware formats (e.g., ‘Today at…’, ‘Yesterday…’, ‘Next Tuesday…’).moment().subtract(1, 'day').calendar(); // 'Yesterday at 3:30 PM'moment().add(3, 'days').calendar(); // 'Sunday at 3:30 PM'moment().calendar(referenceTime, formats); // Customize reference and formats |
| Difference | Calculates the difference between two moments in specified units (default: milliseconds).const start = moment('2023-10-26T09:00:00');const end = moment('2023-10-26T10:30:00');end.diff(start); // Milliseconds differenceend.diff(start, 'minutes'); // 90end.diff(start, 'hours'); // 1end.diff(start, 'hours', true); // 1.5 (floating point) |
| Unix Timestamp (milliseconds) | Gets the number of milliseconds since the Unix Epoch.moment().valueOf();+moment(); // Shorthand using type coercion |
| Unix Timestamp (seconds) | Gets the number of seconds since the Unix Epoch.moment().unix(); |
| Days in Month | Gets the number of days in the current moment’s month.moment('2024-02-01').daysInMonth(); // 29 (leap year)moment('2023-02-01').daysInMonth(); // 28 |
| As JavaScript Date | Converts the Moment object to a native JavaScript Date object.moment().toDate();Caution: Native Date objects have fewer features and different behaviors. |
| As Array | Returns an array mirroring the arguments passed to new Date(): [year, month, day, hour, minute, second, millisecond].moment().toArray(); // e.g., [2023, 9, 26, 15, 30, 0, 0] (Month is 0-indexed) |
| As JSON | Returns an ISO 8601 string suitable for JSON serialization.moment().toJSON(); // Calls moment().toISOString() |
| As ISO 8601 String | Returns the date in ISO 8601 format.moment().toISOString(); // e.g., '2023-10-26T15:30:00.000Z'moment().toISOString(true); // Keep timezone offset if one exists |
| As Object | Returns an object containing date/time components.moment().toObject(); // { years, months, date, hours, minutes, seconds, milliseconds } |
| As String | Returns a human-readable string (uses native Date.prototype.toString).moment().toString(); // e.g., 'Thu Oct 26 2023 15:30:00 GMT+0100' |
| Inspect | Returns the string representation used by Node.js util.inspect(). Primarily for debugging.moment().inspect(); |
Common Format Tokens
Section titled “Common Format Tokens”Some frequently used tokens for moment().format(String):
YYYY: 4-digit year (e.g., 2023)YY: 2-digit year (e.g., 23)MMMM: Full month name (e.g., October)MMM: Short month name (e.g., Oct)MM: Month number (01-12)M: Month number (1-12)DD: Day of month (01-31)D: Day of month (1-31)dddd: Full weekday name (e.g., Thursday)ddd: Short weekday name (e.g., Thu)d: Day of week (0=Sunday, 6=Saturday)HH: Hour (00-23)H: Hour (0-23)hh: Hour (01-12)h: Hour (1-12)mm: Minute (00-59)m: Minute (0-59)ss: Second (00-59)s: Second (0-59)A: AM/PMa: am/pmZ: Timezone offset (e.g., +01:00)ZZ: Timezone offset (e.g., +0100)Do: Day of month with ordinal (e.g., 1st, 2nd)X: Unix timestamp (seconds)x: Unix timestamp (milliseconds)
Refer to the official Moment.js documentation for the complete list of format tokens: https://momentjs.com/docs/#/displaying/format/