5 Steps to add Moment.js to Angular CLI
How to add moment.js to Angular CLI workspace?
Updated: 17 Sep 2020
Introduction
Moment.js is used for parsing, validating, manipulating, and displaying dates and times in JavaScript. In this guide, we are adding Moment.js to Angular (application platform). It is worth noting that alternatives to using Moment.js are:
- date-fns (use libary such as ngx-date-fns is one of the many ways to use date-fns with Angular.)
- Luxon (how to use Luxon with Angular2)
***It is important to note that “Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.” It is because “the effort to make better date and time APIs in the JavaScript language is being done via The ECMA TC39 Temporal Proposal. It is currently at Stage 2 of the TC39 process.” (ref)
Literature Review: Moment.js Vs. date-fns Vs. Luxon
“Moment.js has quite a big performance overhead” according to Matt (2017).
“Luxon = 24.6kB minified & gziped vs 61.4kB for Moment.” according to Buzut (2017).
“Moment.js has a few problems that motivated me to start the project.” according to kossnocorp (2016).
Considerations for using Moment.js (IMO)
- Kind of a de-facto standard for manipulating date and time in JavaScript.
- Usable with Angular Material’s datepicker.
- You don’t (may not) need Moment.js
5 Steps to add Moment.js to Angular CLI workspace
Step 1: Install Angular CLI via terminal i.e. using MacOS
npm install -g @angular/cli
Step 2: again in terminal
ng new my-first-moment-project
cd my-first-moment-project
Step 3: Install Moment via in terminal
npm install moment --save
Step 4: in app.component.ts (.ts is a TypeScript file)
import { Component } from '@angular/core';
import * as moment from 'moment'; // add this 1 of 4
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor() {
let now = moment(); // add this 2 of 4
console.log('hello world', now.format()); // add this 3 of 4
console.log(now.add(7, 'days').format()); // add this 4of 4
}
}