Moment.js

Language: JavaScript

Utility

Moment.js was created to provide a robust, reliable, and easy-to-use API for date manipulation in JavaScript. It became popular due to inconsistencies in the native Date object and its lack of convenient formatting, parsing, and timezone handling capabilities.

Moment.js is a widely-used JavaScript library for parsing, validating, manipulating, and formatting dates and times. It simplifies working with dates across different browsers and time zones.

Installation

npm: npm install moment
yarn: yarn add moment

Usage

Moment.js allows you to create, parse, manipulate, and format dates and times easily. You can chain multiple operations, handle relative times, perform comparisons, and work with time zones using Moment Timezone.

Getting current date and formatting

import moment from 'moment';
const now = moment();
console.log(now.format('YYYY-MM-DD HH:mm:ss'));

Creates a Moment object representing the current date and time, then formats it as a string.

Parsing a date string

const date = moment('2025-08-22', 'YYYY-MM-DD');
console.log(date.format('MMMM Do, YYYY'));

Parses a date string using a specified format and formats it in a human-readable form.

Manipulating dates

let future = moment().add(7, 'days').subtract(2, 'hours');
console.log(future.format());

Adds 7 days and subtracts 2 hours from the current date.

Comparing dates

const date1 = moment('2025-08-22');
const date2 = moment('2025-09-01');
console.log(date1.isBefore(date2)); // true
console.log(date1.isAfter(date2)); // false

Compares two Moment objects to determine their chronological order.

Relative time

const past = moment('2025-08-15');
console.log(past.fromNow());

Displays the relative time from now, e.g., '7 days ago'.

Timezone handling

import 'moment-timezone';
const nyTime = moment.tz('2025-08-22 12:00', 'America/New_York');
console.log(nyTime.format());

Creates a Moment object in a specific timezone using Moment Timezone.

Error Handling

Invalid date: Ensure that the input string matches the expected format or use Moment's strict parsing mode.
Unexpected behavior across browsers: Use Moment.js instead of relying solely on the native Date object to handle inconsistencies.

Best Practices

Use `.clone()` before modifying dates to avoid mutating original Moment objects.

Prefer ISO 8601 strings for parsing to ensure consistency.

Use Moment Timezone when working with different time zones.

Use relative time functions for user-friendly date displays.

Be aware that Moment.js is in maintenance mode; consider alternatives like date-fns or Luxon for new projects.