Format date with Moment.js
Categories:
Mastering Date Formatting with Moment.js
Learn how to effectively format, parse, and manipulate dates and times in JavaScript using the powerful Moment.js library.
Working with dates and times in JavaScript can often be a cumbersome task due to the native Date
object's limitations and inconsistencies across environments. Moment.js emerged as a popular solution, providing a robust, lightweight, and user-friendly API for parsing, validating, manipulating, and formatting dates. While Moment.js is now in maintenance mode, understanding its core functionalities remains valuable for maintaining existing projects or appreciating the evolution of date-time libraries in JavaScript.
Getting Started with Moment.js
Before diving into formatting, let's ensure you have Moment.js set up. You can include it in your project via CDN, npm, or yarn. Once included, the moment()
function becomes globally available, allowing you to create Moment objects.
// Via npm/yarn
// npm install moment
// import moment from 'moment';
// Via CDN in HTML
// <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
const now = moment();
console.log(now.format()); // e.g., 2023-10-27T10:30:00+01:00
Initializing a Moment object to the current date and time.
date-fns
or the native Intl.DateTimeFormat
API for modern JavaScript date handling.Basic Date Formatting
The format()
method is the cornerstone of Moment.js for displaying dates in various human-readable strings. It accepts a format string as an argument, composed of tokens representing different date and time components. Without any arguments, format()
defaults to an ISO 8601 string.
const m = moment(); // Current date and time
console.log(m.format('YYYY-MM-DD')); // 2023-10-27
console.log(m.format('MMMM Do YYYY')); // October 27th 2023
console.log(m.format('dddd, h:mm:ss a')); // Friday, 10:30:45 am
console.log(m.format('DD/MM/YYYY HH:mm')); // 27/10/2023 10:30
Examples of common date format strings using Moment.js.
Common Moment.js Formatting Tokens
Advanced Formatting with Localization
Moment.js offers extensive support for localization, allowing you to format dates according to different language and regional conventions. You can change the locale globally or for individual Moment objects, affecting how month names, day names, and relative times are displayed.
const m = moment();
// Global locale change
moment.locale('es');
console.log(m.format('LLLL')); // viernes, 27 de octubre de 2023 10:30
// Locale for a specific moment object
const frenchMoment = moment().locale('fr');
console.log(frenchMoment.format('LLLL')); // vendredi 27 octobre 2023 10:30
// Reset to default (en)
moment.locale('en');
Demonstrating date formatting with different locales.
Parsing Dates with Moment.js
Beyond formatting, Moment.js excels at parsing various date strings into Moment objects. This is crucial when dealing with user input or data from external sources. You can provide a format string to guide the parsing process, making it more robust.
// Parsing with a known format
const parsedDate1 = moment('27/10/2023', 'DD/MM/YYYY');
console.log(parsedDate1.format('YYYY-MM-DD')); // 2023-10-27
// Parsing an ISO 8601 string (Moment.js handles this by default)
const parsedDate2 = moment('2023-10-27T10:30:00Z');
console.log(parsedDate2.format('MMMM Do, YYYY')); // October 27th, 2023
// Parsing an invalid date
const invalidDate = moment('not a date');
console.log(invalidDate.isValid()); // false
Examples of parsing date strings into Moment objects.
1. Step 1
Include Moment.js in your project using a CDN or package manager.
2. Step 2
Create a Moment object, either for the current time (moment()
) or a specific date (moment('2023-01-15')
).
3. Step 3
Use the .format()
method with a desired format string (e.g., 'YYYY-MM-DD'
) to display the date.
4. Step 4
For localized formatting, change the locale using moment.locale('es')
before formatting.
5. Step 5
To parse date strings, pass the string and optionally a format hint to moment('date string', 'format hint')
.