How to Add Moment JS to an Angular 9

In this quick article, we will discuss how to add moment.js to Angular 9 and how to work with date and time in using a moment.js module.
moment.js is a lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.
Two simple steps require to add moment js in Angular 9 applications.

1. Install Moment in Your App

npm install moment --save

2. Import moment in TypeScript file (Angular ts components)

Import and use in your Typescript file:
import * as moment from 'moment';

Locale Import:

To use the moment.locale you first need to import the language you are targeting.
import * as moment from 'moment';
import 'moment/locale/pt-br';

console.log(moment.locale()); // en
moment.locale('fr');
console.log(moment.locale()); // en
moment.locale('pt-BR');
console.log(moment.locale()); // pt-BR

Usage with an example

import * as moment from 'moment';
import 'moment/locale/pt-br';

export class MomentDemo {

    test() {
        const date = moment();
        let dateInFormat = date.format('YYYY.M.D');
        console.log(dateInFormat);
    }

    localeTest() {
        console.log(moment.locale()); // en
        moment.locale('fr');
        console.log(moment.locale()); // en
        moment.locale('pt-BR');
        console.log(moment.locale()); // pt-BR
    }
}

Reference

Comments