How to use Moment.JS in Angular ?

Moment.js is a lightweight javascript library/package for parsing, validating, manipulating, and formatting dates. It’s designed to simplify working with dates and times in JavaScript, Moment.js can be used in a browser using the script approach. It is also compatible with Node.js and can be installed via npm.
In Angular, Moment.js library simplifies the work with dates and times easily and can be manipulated as our requirements. You can use Moment.js in your Angular project in multiple ways are as follows:

1. Installing Moment.js via npm

This is the most common method for adding Moment.js to an Angular project. Here’s how you can do it:
a. Open your project’s terminal and navigate to the root directory.
b. Run the following command to install Moment.js as a dependency:
npm install moment –save
c. Once the installation is complete, you can import and use Moment.js in your Angular components where you want to use app.component.ts file

import { Component } from '@angular/core';
import moment from 'moment';
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  currentDate: moment.Moment = moment();
 currentTime: string = moment().format('M/D/YYYY hh:mm:ss a');
  format1: string = moment().format('M/D/YYYY');
  format2: string = moment().format('MMMM D, YYYY');
  format3: string = moment().format('YYYY-MM-DD hh:mm A');
  futuredate =this.currentDate.add(1, 'days');
  constructor() {
console.log(moment.locale()); // en


<h1>Current date and Time:<br />{{ currentDate }}</h1>
<h2>Format date 1<br />{{ format1 }}</h2>
<h2>Format date 2<br />{{ format2 }}</h2>
<h2>Format date 3<br />{{ format3 }}</h2>
<h2>Tomorrow's date:<br />{{ futuredate }}</h2>

2. Using CDN

If you prefer not to include Moment.js as a dependency in your project, you can include it directly via a Content Delivery Network (CDN). Here’s how:
a. Add the following < script > tag to the < head > section of your index.html file:
< script src="“>< /script >

b. In your Angular component, you can use Moment.js as mentioned in the previous response, without the need for importing it.

Note: Using a CDN may have performance implications, as it relies on an external resource and may not be as optimized for your specific project.

Subscribe for
weekly updates