Content table:
What is Moment.js, and why is it useful for Angular projects?
How to install and use Moment.js via npm and CDN.
How to format dates, change locales, calculate time differences, and handle time zones in Angular applications.
Moment.js is a JavaScript library that makes date and time manipulation easy. It offers a simple method to parse, validate, manipulate, and format date objects in JavaScript applications, such as Angular applications. With the ability to support a range of formats, locales, and time zones, it has become a favorite solution to date-related problems. Its value is especially clear in legacy applications that need to have uniform date management across multiple browsers and time zones.
Angular applications most often require date and time manipulation for timestamp formatting, UTC date management, interacting with a given moment in time, or calculating date differences. JavaScript's built-in Date object is capable of handling these tasks, while Moment.js offers a friendlier API combined with extensive functionality. It supports internationalization, has UTC mode, and can handle a range of date formats, so it is beneficial in both new projects and legacy projects.
Basic Date Formatting: Moment.js provides a simple way of formatting dates in various formats.
Locale Support: It is simple to modify the locale to display dates in other languages.
Time Zone Support: With moment-time zones, you can convert dates safely to another time zone.
Duration and Date Arithmetic: Easily add or subtract days, months, or years.
Human-Readable Formats: Provides means to display dates in user-readable formats.
Consistent Date Parsing: Avoids typical JavaScript date-related pitfalls.
There are multiple ways to integrate Moment.js into an Angular project, which we will cover below. The most simplest way to add Moment.js to an Angular app is by installing it via npm.
Follow these steps:
Open your terminal, navigate to your Angular CLI project’s root directory, and run the following command:
npm install moment --save
This command will download and add Moment.js as a dependency in your project. If you need moment-timezone support, install it using:
npm install moment-timezone
After installation, you need to import Moment.js in your TypeScript (.ts) file where you plan to use it. Open app.component.ts and add the following code:
import { Component } from '@angular/core';
import * as moment from 'moment';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentDate: moment.Moment = moment();
currentTime: string = moment().format('MM/DD/YYYY hh:mm:ss A');
format1: string = moment().format('MM/DD/YYYY');
format2: string = moment().format('MMMM D, YYYY');
format3: string = moment().format('YYYY-MM-DD hh:mm A');
futureDate = this.currentDate.clone().add(1, 'days');
utcDate = moment.utc().format();
constructor() {
console.log('Current Locale:', moment.locale()); // Default is 'en'
}
}
To show the formatted dates in your Angular template, update app.component.html as follows:
<h1>Current Date and Time:<br />{{ currentTime }}</h1>
<h2>Formatted Date 1:<br />{{ format1 }}</h2>
<h2>Formatted Date 2:<br />{{ format2 }}</h2>
<h2>Formatted Date 3:<br />{{ format3 }}</h2>
<h2>Tomorrow's Date:<br />{{ futureDate.format('MMMM D, YYYY') }}</h2>
<h2>UTC Date:<br />{{ utcDate }}</h2>
If you do not want to install Moment.js as a package, you can use it directly from a Content Delivery Network (CDN). This is useful for quick testing in an Angular project.
Add the following <script> tag inside the <head> section of your index.html file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Since Moment.js is now globally available, you don’t need to import it in your TypeScript files. You can use it directly within your component like this:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentDate = (window as any).moment();
formattedDate = (window as any).moment().format('YYYY-MM-DD HH:mm:ss');
}
Installation Options: Install Moment.js using npm install moment --save or via a CDN.
Flexible Date Handling: Format and convert date objects using methods such as moment().format().
Time Zones and Localization: moment-timezone optimizes handling time zones.
Human-Readable Output: Present dates in a readable format using moment().calendar().
Handling UTC and Offsets: Handle UTC and local times with ease.
Alternatives: Since Moment.js is in maintenance mode, date-fns or Luxon can be used in new Angular projects instead.
Moment.js is still a favored option for handling dates in Angular, mostly for existing projects that utilize it. However, newer libraries provide better optimization for modern development. Although Moment.js is still an excellent choice, it is currently in maintenance mode. If you are initiating a new Angular project, use date-fns or Luxon for contemporary development, particularly when the strong support for TypeScript and modular imports is needed.For existing projects, Moment.js is still a good option to use for date operations effectively.
This website uses cookies to analyze website traffic and optimize your website experience. By continuing, you agree to our use of cookies as described in our Privacy Policy.