Moment.js: Complete explanation and practical examples of the date library

Last update: July 28, 2025
  • Moment.js simplifies date and time management in JavaScript with a clean and powerful API.
  • Allows you to analyze, manipulate, validate, and display dates in any format and time zone.
  • It integrates easily into projects and is compatible with external plugins and libraries such as IronPDF.

moment.js

Working with dates and times in JavaScript can be a real challenge for web developers . Luckily, tools like Moment.js significantly simplify this process, making everything from basic date formatting to complex manipulation and validation operations much easier. If you've ever felt frustrated trying to convert, compare, or display dates correctly in your projects, Moment.js has probably been one of your best friends, or at least you should consider using it.

In this article, I'll tell you everything you need to know about Moment.js : from its main functions and lesser-known tricks, to practical examples and its integration with other libraries, including a clear explanation of its syntax and the tasks you can accomplish with it. We'll also look at its limitations, recent updates, and what alternatives you have if you're looking for something more modern.

What is Moment.js and why has it become so popular?

Moment.js is a JavaScript library designed to make working with dates and times effortless . It allows you to create, parse, manipulate, and display dates in virtually any format imaginable with a simple yet powerful syntax. For years, this library has been the community's primary solution for overcoming the limitations of JavaScript's native Date() object.

The core of Moment.js revolves around the `moment()` object , which can construct dates from almost any valid input: text strings, Date objects, timestamps, or directly with numeric arguments. This makes it extremely flexible and useful in all kinds of projects, from small scripts to enterprise applications that manage international time zones or historical records.

What has made it so successful? Its reliability, ease of use, and the variety of accompanying tools and plugins . Even when the project has entered maintenance mode, Moment.js maintains a large user base and extensive documentation , reinforcing its position as a leading date solution in JavaScript and Node.js.

  What is Scratch: A Complete Guide to Learning and Teaching Visual Programming

Key features and benefits of Moment.js

  • Simple and intuitive APIOne of Moment.js's greatest strengths is its clear syntax. You can perform simple operations, such as getting the current date or converting a string to a specific format, or complex calculations and validations in just a few lines.
  • Flexible parsing and formattingParsing date strings of almost any format and converting them to the desired output has never been easier. Moment.js makes it quick and painless to format dates in custom presentations..
  • Date manipulation: Adding or subtracting days, months, years, weeks, or any other unit of time is as simple as using the methods add () y subtract()This is very useful when you need to work with relative dates, due dates, or timeframes that vary dynamically.
  • Robust validation: If you need to check if a date is valid or exists (for example, February 30th), Moment.js makes it easy for you. The method isValid() It is able to detect subtle errors in the format or logic of dates.
  • Support for time zones and localization: Thanks to your plugin moment-timezoneIt's very easy to convert dates between different time zones. You can also display dates adapted to the user's language and regional conventions, which is key in global applications.
  • Plugin ecosystem: Apart from the main library, there is an ecosystem of plugins to extend its functionality (calendar, compatibility with other frameworks, exotic formats...).

How to get started with Moment.js in your project

Installation is very straightforward . You can include Moment.js in your HTML with a single line:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

If you're working with Node.js or a modern development environment, it's common to install it using npm or yarn:

npm install moment

Once this is done, you can import Moment.js according to the syntax you use:

// Versión CommonJS
var moment = require('moment');
moment().format();

// ES6
import moment from 'moment';
moment().format();

Creating dates: different ways and practical examples

Create dates easily

To get the current date and time, simply use moment():

console.log(moment()); // Devuelve la fecha actual en formato ISO8601

You can construct a specific date by passing arguments:

moment("2022-10-14"); // Crea el 14 de octubre de 2022

You can also start from a given string and format, even in strict mode:

moment("25/12/1995", "DD/MM/YYYY", true); // Analiza y comprueba el formato

Do you have a native Date object?

const fechaJS = new Date();
const miFecha = moment(fechaJS);

Formatting and displaying dates

Moment.js allows you to display dates in any imaginable format . For example, to display the current date as day/month/year:

moment().format('DD/MM/YYYY');

If you want a more humanized chain, you can use:

moment().format('MMMM Do YYYY, h:mm:ss a'); // Ejemplo: "marzo 8º 2024, 3:21:10 pm"

Some useful tokens for formatting :

  • YYYY: 4-digit year
  • MM: my
  • DD: day of the month
  • hh o HH: time (12h or 24h format)
  • mm: minutes
  • ss: seconds
  • a: am/pm
  Advantages of Gemini Coder over other AI programming assistants

For example, to display only the time:

moment().format('HH:mm:ss');

Advanced formatting with tokens and regional support

Moment.js supports multiple localized formats and translations . It's possible to switch languages ​​on the fly to display month and day names in another language.

moment.locale('es'); // Cambia a español
document.write(moment().format('LLLL'));
// Ejemplo: martes, 8 de marzo de 2024 15:21

Date manipulation: addition, subtraction, and comparison

Working with relative dates is one of Moment.js' strengths.

  • Add days, months or years:
    moment().add(3, 'days').format('DD/MM/YYYY');
  • Subtract units:
    moment().subtract(2, 'months').format('DD/MM/YYYY');
  • Start and end of periods:
    moment().startOf('month').format('DD/MM/YYYY'); // Primer día del mes
    moment().endOf('month').format('DD/MM/YYYY');   // Último día del mes

Validate dates and detect errors

Before operating with dates it is vital to validate that they are correct:

moment('2024-02-30', 'YYYY-MM-DD').isValid(); // false, el 30 de febrero no existe

This prevents unexpected bugs in applications that receive dates from the user.

Date comparison: check if a date is among others

Moment.js includes several methods for comparing dates:

  • isBefore(): Checks if one date is before another.
  • isAfter(): Checks if a date is later.
  • isBetween(): Indicates whether a date is between two given dates.
let hoy = moment();
let ayer = moment().subtract(1, 'days');
console.log(hoy.isAfter(ayer)); // true

Handling time zones and international dates

When working with users in different parts of the world, time zones can be a real headache . With the moment-timezone plugin , you can easily convert dates between regions.

const moment = require('moment-timezone');
const fechaUTC = moment('2024-05-25');
const fechaNY = fechaUTC.tz('America/New_York').format('YYYY-MM-DD HH:mm:ss');
console.log(fechaNY);
// Ejemplo: "2024-05-24 20:00:00"

In addition, Moment.js is able to display dates adapted to the user's regional settings , showing correctly translated month and day names.

Key usage examples and advanced tips

Get differences between dates

You can calculate the time elapsed between two dates in different units:

let inicio = moment('2024-01-01');
let fin = moment('2024-03-08');
let dias = fin.diff(inicio, 'days'); // Devuelve el número de días entre ambas

Relative dates and human times

Moment.js is great for displaying messages like "3 days ago" or "in 5 hours":

moment().subtract(3, 'days').fromNow(); // "hace 3 días"
moment().add(2, 'hours').fromNow();    // "en 2 horas"

Human calendar

The calendar() function displays relative dates such as "yesterday at 17:00 PM", "tomorrow at 9:00 AM", making it very usable for calendar apps.

moment().subtract(1, 'days').calendar(); // "Ayer a las..."
moment().add(3, 'days').calendar();     // "Próximo martes a las..."

Support for year jumps and special days

Do you want to know if a year is a leap year?

moment([2024]).isLeapYear(); // true

The isLeapYear() method gives you the answer directly.

  Mastering Software Unit Testing

Advanced customization: formats, tokens, and strict parsing

Moment.js allows you to work with custom strings and tokens to create or read dates in countless formats . Furthermore, strict mode requires exact matches, preventing subtle errors and unwanted surprises.

For example, to parse a date in the format "day/month/year":

moment('12/03/2023', 'DD/MM/YYYY', true);

List of common tokens and examples

  • Year: YYYY (2024), YY (24), Y (-500)
  • Month: MM (01 – 12), MMM (Jan), MMMM (January)
  • Daytime: DD (01 – 31), C (1st – 31st)
  • Time: HH (00 – 23), hh (01 – 12), mm (minutes), ss (seconds)
  • Time zone: Z, ZZ

These tokens can be combined to create completely customized outputs. See the documentation for the full list and special cases.