How to use Moment JS in Angular 17?

By Hardik Savani November 28, 2023 Category : Angular

Hello everyone,

If you're seeking guidance on installing Moment.js in Angular 17, you've come to the right place. In this tutorial, I'll walk you through the process of adding Moment.js to your Angular 17 project. I'll also share insights on how to effectively use Moment.js within an Angular 17 environment. Let's delve into the details of importing Moment.js in Angular 17.

In this tutorial, I will give you very simple steps to install moment js in the angular 17 application.

Step for Angular 17 Install Moment JS

  • Step 1: Create Angular 17 Project
  • Step 2: Install Moment JS
  • Step 3: Add Moment in Component ts File
  • Step 4: Use New Component
  • Run Angular App

so let's follow steps here:

Step 1: Create Angular 17 Project

You can easily create your angular app using below command:

ng new my-new-app

Step 2: Install Moment JS

You have to run the bellow command to install moment js npm package in angular.

npm install moment --save

Step 3: Add Moment in Component ts File

Let's use bellow code for component file.

so, let's update as like bellow:

src/app/app.component.ts

import { Component } from '@angular/core';

import { CommonModule } from '@angular/common';

import { RouterOutlet } from '@angular/router';

import moment from 'moment';

@Component({

selector: 'app-root',

standalone: true,

imports: [CommonModule, RouterOutlet],

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent {

title = 'firstApp';

todayDate = '';

constructor() {

this.test();

}

test() {

const date = moment();

this.todayDate = date.format('M/D/YYYY');

console.log(this.todayDate);

}

}

Step 4: Update Component HTML File

Let's use bellow code for component file.

so, let's update as like bellow:

src/app/app.component.html

<h1>How to use Moment.js in Angular 17 - ItSolutionStuff.Com</h1>

<strong>Today Date: {{ todayDate }}</strong>

Run Angular App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Angular app:

ng serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:4200

Output:

i hope it can help you...

Shares