Home ยป Moment.js Tutorial with Examples

Moment.js Tutorial with Examples

Moment.js is a powerful JavaScript library for parsing, validating, manipulating, and formatting dates and times.

It simplifies working with dates and times in JavaScript by offering intuitive methods to handle common date/time-related tasks.

In this tutorial, we will cover:

  1. Introduction to Moment.js
  2. Installation and Setup
  3. Creating and Formatting Dates
  4. Manipulating Dates (Add, Subtract, etc.)
  5. Parsing Dates
  6. Working with Time Zones
  7. Comparing Dates
  8. Formatting Dates for Output
  9. Examples and Use Cases

Let's explore each concept with examples.

1. Introduction to Moment.js

JavaScript's native Date object has limited functionality, making it challenging to perform complex date manipulations. Moment.js provides a more user-friendly API for working with dates, enabling you to:

  • Format dates and times.
  • Add or subtract time units (days, months, years, etc.).
  • Parse strings into dates.
  • Compare dates.
  • Handle time zones.

2. Installation and Setup

Installing Moment.js via npm or yarn

npm install moment

or

yarn add moment

CDN for Browser Use

For using Moment.js in the browser, you can include it directly via CDN:

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

Importing Moment.js in your project

const moment = require('moment');

// ES6 import
import moment from 'moment';

3. Creating and Formatting Dates

You can create and manipulate dates using Moment.js in various formats.

Example 1: Creating the Current Date

// Create a moment object for the current date and time
const now = moment();
console.log(now.format());  // Output: Current date and time in ISO format

Example 2: Formatting a Date

// Create a moment object and format it
const formattedDate = moment().format('MMMM Do YYYY, h:mm:ss a');
console.log(formattedDate);  // Output: e.g., "October 17th 2024, 4:30:22 pm"

In this example:

  • MMMM gives the full month name (e.g., “October”).
  • Do gives the day of the month with an ordinal suffix (e.g., “17th”).
  • YYYY gives the four-digit year.
  • h:mm:ss a gives the time in 12-hour format with seconds and AM/PM.

Example 3: Creating a Specific Date

You can create specific dates by passing arguments to the moment() constructor.

const specificDate = moment([2023, 9, 15]);  // October 15, 2023
console.log(specificDate.format('YYYY-MM-DD'));  // Output: "2023-10-15"

Here, months are zero-indexed, so 9 corresponds to October.


4. Manipulating Dates (Add, Subtract, etc.)

Moment.js makes it easy to manipulate dates by adding or subtracting time units like days, months, years, etc.

Example 1: Adding Time to a Date

const futureDate = moment().add(10, 'days');  // Add 10 days to the current date
console.log(futureDate.format('YYYY-MM-DD'));  // Output: The date 10 days from now

Example 2: Subtracting Time from a Date

const pastDate = moment().subtract(2, 'months');  // Subtract 2 months from the current date
console.log(pastDate.format('YYYY-MM-DD'));  // Output: The date 2 months ago

Example 3: Chaining Date Manipulations

const manipulatedDate = moment().add(2, 'weeks').subtract(3, 'days');
console.log(manipulatedDate.format('YYYY-MM-DD'));  // Output: 2 weeks ahead, minus 3 days

5. Parsing Dates

Moment.js allows you to parse date strings in various formats.

Example 1: Parsing a Date from a String

const parsedDate = moment('2024-10-17', 'YYYY-MM-DD');
console.log(parsedDate.format('MMMM Do, YYYY'));  // Output: "October 17th, 2024"

In this example:

  • We parse the date string “2024-10-17” using the format “YYYY-MM-DD”.

Example 2: Parsing a Date with Time

const parsedDateTime = moment('2024-10-17 14:30:00', 'YYYY-MM-DD HH:mm:ss');
console.log(parsedDateTime.format('MMMM Do YYYY, h:mm:ss a'));  // Output: "October 17th 2024, 2:30:00 pm"

You can specify a format that matches the input date string to ensure correct parsing.

6. Working with Time Zones

Moment.js has a companion library called moment-timezone for handling time zones.

Installation of moment-timezone

npm install moment-timezone

Example: Working with Time Zones

const moment = require('moment-timezone');

// Set the timezone to 'America/New_York'
const newYorkTime = moment().tz('America/New_York').format('MMMM Do YYYY, h:mm:ss a');
console.log('New York Time:', newYorkTime);

// Set the timezone to 'Asia/Tokyo'
const tokyoTime = moment().tz('Asia/Tokyo').format('MMMM Do YYYY, h:mm:ss a');
console.log('Tokyo Time:', tokyoTime);

In this example, we use moment-timezone to convert the current time to different time zones.

7. Comparing Dates

Moment.js provides several methods for comparing dates.

Example 1: Checking if a Date is Before or After Another

const date1 = moment('2024-10-01');
const date2 = moment('2024-10-17');

console.log(date1.isBefore(date2));  // Output: true
console.log(date2.isAfter(date1));   // Output: true

Example 2: Checking if Two Dates Are the Same

const date1 = moment('2024-10-17');
const date2 = moment('2024-10-17');

console.log(date1.isSame(date2));  // Output: true

Example 3: Checking if a Date is Between Two Dates

const startDate = moment('2024-10-01');
const endDate = moment('2024-10-31');
const checkDate = moment('2024-10-15');

console.log(checkDate.isBetween(startDate, endDate));  // Output: true

8. Formatting Dates for Output

Moment.js allows you to format dates in many different ways using predefined or custom formats.

Example 1: Using Predefined Formats

const now = moment();

// ISO 8601 format
console.log(now.toISOString());  // Output: "2024-10-17T10:30:15.123Z"

// Unix timestamp
console.log(now.unix());  // Output: Unix timestamp in seconds

Example 2: Custom Formatting

const formattedDate = moment().format('dddd, MMMM Do YYYY, h:mm:ss a');
console.log(formattedDate);  // Output: e.g., "Thursday, October 17th 2024, 4:30:00 pm"

In this example:

  • dddd gives the full day name (e.g., “Thursday”).
  • MMMM gives the full month name (e.g., “October”).
  • Do gives the day of the month with an ordinal (e.g., “17th”).
  • h:mm:ss a gives the time in 12-hour format with AM/PM.

9. Examples and Use Cases

Example 1: Displaying Time Ago (Relative Time)

Moment.js can display relative time (e.g., “5 minutes ago”, “2 days ago”).

const pastDate = moment('2024-10-15');
console.log(pastDate.fromNow());  // Output: "2 days ago"

Example 2: Calculating Duration Between Two Dates

You can calculate the duration (difference) between two dates in various units such as days, hours, or minutes.

const date1 = moment('2024-10-01');
const date2 = moment('2024-10-17');

// Get the difference in days
const differenceInDays = date2.diff(date1, 'days');
console.log(`Difference in days: ${differenceInDays}`);  // Output: "16 days"

Example 3: Formatting Dates for Different Locales

Moment.js supports multiple locales for date formatting.

// Set the locale to French
moment.locale('fr');
console.log(moment().format('LLLL'));  // Output in French format

// Set the locale back to English
moment.locale('en');
console.log(moment().format('LLLL'));  // Output in English format

Example 4: Counting Down to a Future Date

You can use Moment.js to create

countdowns to future events.

const eventDate = moment('2024-12-25');
const daysUntilEvent = eventDate.diff(moment(), 'days');
console.log(`Days until event: ${daysUntilEvent}`);  // Output: Number of days until Christmas 2024

Summary of Moment.js Key Methods

Method Description
moment() Creates a new moment object for the current date and time.
format() Formats the date using a custom or predefined format.
add() Adds time to the moment object (e.g., days, months).
subtract() Subtracts time from the moment object.
isBefore() / isAfter() Checks if one date is before or after another.
isSame() Checks if two dates are the same.
diff() Returns the difference between two dates in specified units.
fromNow() Displays relative time (e.g., “5 minutes ago”).
locale() Sets or gets the locale for date formatting.
toISOString() Converts the date to ISO 8601 format.
unix() Returns the Unix timestamp for the date.

Conclusion

Moment.js simplifies working with dates and times in JavaScript by providing intuitive methods for creating, manipulating, formatting, and comparing dates. In this tutorial, we covered:

  • Creating and formatting dates with Moment.js.
  • Manipulating dates by adding or subtracting time units.
  • Parsing strings into dates.
  • Working with time zones and comparing dates.
  • Formatting dates for output in various formats.

You may also like