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.
npm install momentyarn add momentMoment.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.
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.
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.
let future = moment().add(7, 'days').subtract(2, 'hours');
console.log(future.format());Adds 7 days and subtracts 2 hours from the current date.
const date1 = moment('2025-08-22');
const date2 = moment('2025-09-01');
console.log(date1.isBefore(date2)); // true
console.log(date1.isAfter(date2)); // falseCompares two Moment objects to determine their chronological order.
const past = moment('2025-08-15');
console.log(past.fromNow());Displays the relative time from now, e.g., '7 days ago'.
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.
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.