How to Format a Date With Moment.Js in Javascript

Avatar

By squashlabs, Last Updated: December 9, 2023

How to Format a Date With Moment.Js in Javascript

Formatting dates is a common task in JavaScript, and Moment.js is a popular library that makes it easier to work with dates and times. Moment.js provides a simple and intuitive API for parsing, manipulating, and displaying dates and times. In this answer, we will explore how to format dates using Moment.js in JavaScript.

Step 1: Installing Moment.js

To start using Moment.js, you need to include it in your project. There are a few ways to install Moment.js, but the most common method is through npm, the Node.js package manager. You can install Moment.js by running the following command in your project directory:

npm install moment

Alternatively, you can include Moment.js directly in your HTML file by adding the following script tag:


Related Article: Accessing Parent State from Child Components in Next.js

Step 2: Importing and Using Moment.js

Once you have installed Moment.js, you can import it into your JavaScript file using the require or import statement:

const moment = require('moment');
// or
import moment from 'moment';

With Moment.js imported, you can now use its functions to format dates.

Step 3: Formatting Dates

Moment.js provides the format function to format dates. This function takes a formatting string as an argument and returns the formatted date string.

Here are some common formatting tokens that you can use in the formatting string:

YYYY: 4-digit year
YY: 2-digit year
MM: 2-digit month (01-12)
DD: 2-digit day of the month (01-31)
HH: 2-digit hour (00-23)
mm: 2-digit minute (00-59)
ss: 2-digit second (00-59)

For example, to format the current date as “YYYY-MM-DD”, you can use the following code:

const formattedDate = moment().format('YYYY-MM-DD');
console.log(formattedDate); // Output: 2022-01-01

You can also pass a specific date to the moment function to format that date:

const date = moment('2021-12-25');
const formattedDate = date.format('dddd, MMMM Do YYYY');
console.log(formattedDate); // Output: Saturday, December 25th 2021

Step 4: Localizing Date Formats

Moment.js provides built-in support for localizing date formats. You can set the locale using the locale function and then format the date accordingly.

Here’s an example of formatting a date in French:

moment.locale('fr');
const formattedDate = moment().format('LL');
console.log(formattedDate); // Output: 1er janvier 2022

You can find a list of available locales in the Moment.js documentation.

Related Article: How to Integrate Redux with Next.js

Step 5: Additional Formatting Options

In addition to the basic formatting tokens, Moment.js provides many other options for formatting dates. Here are a few examples:

Do: Day of the month with ordinal suffix (1st, 2nd, 3rd, etc.)
ddd: Abbreviated weekday name (Sun, Mon, Tue, etc.)
MMMM: Full month name (January, February, March, etc.)
h: Hour (1-12)
A: Uppercase AM or PM

You can find a comprehensive list of formatting tokens in the Moment.js documentation.

Step 6: Best Practices

When formatting dates with Moment.js, it’s important to follow some best practices to ensure consistent and reliable results:

– Use the appropriate formatting tokens for the desired output. Moment.js provides a wide range of formatting options, so choose the ones that match your requirements.
– Consider the locale when formatting dates. Moment.js supports localization, allowing you to display dates in different languages and formats.
– Test your date formats thoroughly to ensure they work as expected in different scenarios, such as different time zones or leap years.

You May Also Like

nvm (Node Version Manager): Install Guide & Cheat Sheet

Learn to manage Node.js versions with nvm (Node Version Manager). This guide and cheat sheet will help you use nvm to install, manage, and switch between different... read more

How to Use the forEach Loop with JavaScript

Learn how to use JavaScript's forEach method for array iteration and explore advanced topics beyond basic array manipulation. Discover best practices, common mistakes,... read more

How to Use Javascript Substring, Splice, and Slice

JavaScript's substring, splice, and slice methods are powerful tools that can help you extract and manipulate data in strings and arrays. Whether you need to format a... read more

JavaScript Arrays: Learn Array Slice, Array Reduce, and String to Array Conversion

This article is a comprehensive guide that dives into the basics and advanced techniques of working with JavaScript arrays. From understanding array syntax to... read more

JavaScript HashMap: A Complete Guide

This guide provides an essential understanding of implementing and utilizing HashMaps in JavaScript projects. This comprehensive guide covers everything from creating... read more

Conditional Flow in JavaScript: Understand the ‘if else’ and ‘else if’ Syntax and More

Conditional Flow in JavaScript: Understand the 'if else' and 'else if' Syntax and More Gain clarity on logical conditions and enhance your JavaScript development by... read more