Angular Material Datepicker Format
July 07, 2020
This page will walk through Angular Material Datepicker format example. Angular Material provides MAT_DATE_FORMATS
object which is the collection of formats used by Datepicker to parse and display dates. To use custom date format we need to override MAT_DATE_FORMATS
with given formats. The MAT_DATE_FORMATS
is used by DateAdapter
of Datepicker and hence our custom date formats should be compatible to the DateAdapter
used by our application.
Here on this page we will provide complete detail to parse and display dates by our Datepicker using custom date formats with
moment.js
.
Contents
1. Technologies Used
Find the technologies being used in our example.1. Angular 10.0.0
2. Angular Material 10.0.0
3. Node.js 12.5.0
4. NPM 6.9.0
5. moment.js 2.27.0
2. Create Custom Date Format
Create a custom date format for parsing and displaying by Datepicker.my-date-formats.ts
export const MY_DATE_FORMATS = { parse: { dateInput: 'DD-MM-YYYY', }, display: { dateInput: 'MMM DD, YYYY', monthYearLabel: 'MMMM YYYY', dateA11yLabel: 'LL', monthYearA11yLabel: 'MMMM YYYY' }, };
(1)
parse: { dateInput: 'DD-MM-YYYY', }
dateInput
property in parse section is the date format in which a user enters date manually in input box. Using this date format Datepicker parses the input date and then displays it in its display date input format.
(2)
display: { dateInput: 'MMM DD, YYYY', }
dateInput
property in display section is the date format in which Datepicker displays the date in input box. Either date can be selected from calendar or date can be entered manually. Finally Datepicker will display date in display date input format.
(3)
display: { monthYearLabel: 'MMMM YYYY', }
monthYearLabel
property in display section is the date format in which calendar displays the month-year label.
(4)
display: { dateA11yLabel: 'LL', monthYearA11yLabel: 'MMMM YYYY' }
dateA11yLabel
and monthYearA11yLabel
properties are related to Accessibility (a11y).
The Accessibility (a11y) project is community driven effort to make web accessibility easier for all people including those with disabilities or impairments. The Accessibility (a11y) project emphasizes to make a system accessible to the people with disabilities such as visual impairment, hearing loss etc.
3. Configure MAT_DATE_FORMATS to use Custom Date Format
We have created custom parse and display format asMY_DATE_FORMATS
in the above section. Now we need to configure it in our application module with MAT_DATE_FORMATS
.
Let us know some points.
1. Angular Material uses
DateAdapter
to create a Datepicker such as NativeDateAdapter
, MomentDateAdapter
or custom DateAdapter
.
2. The
DateAdapter
can be provided by MatNativeDateModule
, MatMomentDateModule
, or a custom implementation.
3. The
MatNativeDateModule
provides NativeDateAdapter
and MatMomentDateModule
provides MomentDateAdapter
.
4. The
MatNativeDateModule
and MatMomentDateModule
use default parse and display formats.
5. The
NativeDateModule
and MomentDateModule
without Mat
-prefix, does not contain default parse and display formats. So for custom date formats we should import NativeDateModule
or MomentDateModule
.
6. The
NativeDateModule
uses native JavaScript date and MomentDateModule
uses Moment
from moment.js
.
7. To provide custom date format we need to configure
MAT_DATE_FORMATS
either with NativeDateModule
or MomentDateModule
.
Find the code snippet to configure
MAT_DATE_FORMATS
in application module. Here we are importing MomentDateModule
.
app.module.ts
import { MatInputModule } from '@angular/material/input'; import { MatDatepickerModule } from '@angular/material/datepicker'; import { MomentDateModule } from '@angular/material-moment-adapter'; import { MAT_DATE_FORMATS } from '@angular/material/core'; import { MY_DATE_FORMATS } from './my-date-formats'; @NgModule({ imports: [ MatInputModule, MatDatepickerModule, MomentDateModule ], providers: [ { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS } ], ------ }) export class AppModule { }
4. moment.js
Themoment.js
is free and open source JavaScript library. The moment.js
is the wrapper on native JavaScript Date
. The moment.js
can be used to parse and display dates using MomentDateModule
or MatMomentDateModule
.
To start working with
moment.js
in our application we need to install it as following.
npm install moment --save
YYYY ( 2019)
YY (19)
MM (11)
MMM (Jun)
MMMM (June)
DD (25)
Find some locale aware formats with examples.
L (14/08/2019)
LL (August 14 2019)
5. Set Date with moment.js
To set date withmoment.js
, we need to import moment
in our component.
import * as _moment from 'moment'; const moment = _moment;
moment
to our FormControl
as following.
this.studentForm.patchValue({ dateOfBirth: moment("12/25/1995", "MM/DD/YYYY"), admDateRange: { startDate: moment("June 01, 2020", "MMM DD,YYYY"), endDate: moment("July 31, 2020", "MMM DD,YYYY") } });
moment
in following ways.
1.
moment()
2.
moment("10-20-1990", "MM-DD-YYYY")
3.
moment("2019-10-20 6:30 +0000", "YYYY-MM-DD HH:mm Z")
4.
moment([2019, 5, 14, 15, 25, 50, 525])
moment
can be instantiated using array with given format.
[year, month, day, hour, minute, second, millisecond]
moment([2019, 5, 14])
6. Get Date as Moment from Datepicker
We have created the Datepicker usingmoment.js
. We can fetch date as Moment
in our component as following.
Import the
Moment
.
import { Moment } from 'moment';
Moment
data type variable.
let dateOfBirth: Moment = this.studentForm.get('dateOfBirth').value; let yearOfBirth = dateOfBirth.toObject().years;
7. Complete Example
my-date-formats.tsexport const MY_DATE_FORMATS = { parse: { dateInput: 'DD-MM-YYYY', }, display: { dateInput: 'MMM DD, YYYY', monthYearLabel: 'MMMM YYYY', dateA11yLabel: 'LL', monthYearA11yLabel: 'MMMM YYYY' }, };
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatInputModule } from '@angular/material/input'; import { MatDatepickerModule } from '@angular/material/datepicker'; import { MomentDateModule } from '@angular/material-moment-adapter'; import { MAT_DATE_FORMATS } from '@angular/material/core'; import { AppComponent } from './app.component'; import { StudentComponent } from './student.component'; import { MY_DATE_FORMATS } from './my-date-formats'; @NgModule({ declarations: [ AppComponent, StudentComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, BrowserAnimationsModule, MatInputModule, MatDatepickerModule, MomentDateModule ], providers: [ { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS } ], bootstrap: [ AppComponent ] }) export class AppModule { }
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl } from '@angular/forms'; import { StudentService } from './student.service'; import * as _moment from 'moment'; import { Moment } from 'moment'; const moment = _moment; @Component({ selector: 'app-student', templateUrl: './student.component.html' }) export class StudentComponent implements OnInit { constructor(private formBuilder: FormBuilder, private studentService: StudentService) { } ngOnInit() { } studentForm = this.formBuilder.group({ name: '', dateOfBirth: '', admDateRange: this.formBuilder.group({ startDate: '', endDate: '' }) }); onFormSubmit() { this.studentService.saveStudent(this.studentForm.value); let dateOfBirth: Moment = this.studentForm.get('dateOfBirth').value; console.log(dateOfBirth.toObject()); let yearOfBirth = dateOfBirth.toObject().years; console.log('yearOfBirth : ', yearOfBirth); this.studentForm.reset(); } setDefaultDate() { this.studentForm.patchValue({ dateOfBirth: moment("12/25/1995", "MM/DD/YYYY"), admDateRange: { startDate: moment("June 01, 2020", "MMM DD,YYYY"), endDate: moment("July 31, 2020", "MMM DD,YYYY") } }); } }
<h3>Datepicker Format</h3> <form [formGroup]="studentForm" (ngSubmit)="onFormSubmit()"> <mat-form-field> <mat-label>Student Name</mat-label> <input matInput formControlName="name"> </mat-form-field> <br/> <mat-form-field appearance="fill"> <mat-label>Date of Birth</mat-label> <input matInput [matDatepicker]="dob" formControlName="dateOfBirth"> <mat-datepicker-toggle matSuffix [for]="dob"></mat-datepicker-toggle> <mat-datepicker #dob></mat-datepicker> </mat-form-field> <br/> <mat-form-field appearance="fill"> <mat-label>Admission Date Range</mat-label> <mat-date-range-input [rangePicker]="admDateRangePicker" formGroupName="admDateRange"> <input matStartDate formControlName="startDate" placeholder="Start date"> <input matEndDate formControlName="endDate" placeholder="End date"> </mat-date-range-input> <mat-datepicker-toggle matSuffix [for]="admDateRangePicker"></mat-datepicker-toggle> <mat-date-range-picker #admDateRangePicker></mat-date-range-picker> </mat-form-field> <br/><br/> <button mat-raised-button>Submit</button> <button mat-raised-button type="button" (click)="setDefaultDate()">Set Default Dates</button> </form>
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class StudentService { saveStudent(student) { console.log(JSON.stringify(student)); } }
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <app-student></app-student> ` }) export class AppComponent { }
8. Run Application
To run the application, find the steps.1. Install Angular CLI using link.
2. Install Angular Material using link.
3. Download source code using download link given below on this page.
4. Use downloaded src in your Angular CLI application.
5. Run ng serve using command prompt.
6. Access the URL http://localhost:4200
Find the print screen of the output.
9. References
DatepickerMoment.js Documentation