How to change date format in Angular 8 using moment.js?

Aman Sharma

If you are using mat date picker and you want date in “YYYY/MM/DD” format for further processing. We can achieve this using moment.js.
moment.js is a JavaScript date library for parsing, validating, manipulating, and formatting dates. In next article we will learn more about moment.js.

1.       Add/Install moment.js:

 npm install moment --save

2.       Import moment in Angular component (.ts file)

import * as moment from 'moment';

3.       Get Date string in "YYYY/MM/DD" format

this.MyDateString = moment(new Date(this.form.controls.myDate.value)).format("YYYY/MM/DD").toString();

It will return string  "YYYY/MM/DD" format

4.       Date Picker in HTML(component.html file)

<input matInput [matDatepicker]="picker1" (click)=""
placeholder="Issue Date" formControlName="myDate" required>
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1 touchUi startView="month"></mat-datepicker>

Post a Comment

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !