How to Add Moment JS to an Angular 10

In this quick article, we will discuss how to add moment.js to Angular 10 application and how to work with date and time using a moment.js module.
The moment.js library is a lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.
Also, check out moment js integration with Angular 6/7/8/9 -
Two simple steps require to add moment js in Angular 10 applications.

1. Install Moment in Your App

npm install moment --save

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

Import and use moment 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

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments