User interface
Angular Material SPA Typescript Visual Studio Code

Using Material Date Pickers in an Angular Application

Welcome to today’s post.

In today’s post I will discuss the use and presentation of dates using the Angular Material Date Picker component.

Among the tasks I will demonstrate in today’s post is:

  1. How to deal with the display of dates in an Angular application with the Material Date Picker UI.
  2. How to set dates from the Material Date Picker component.
  3. How to retrieve dates from a Material Date Picker component.

The first task is to retrieve data into a Material Date Picker.

We could quite easily set the input value through a fixed value. That would be quite simple to do, so instead, I will show how to read data into a date picker from a backend store or API.

Reading Data from a Date Picker Component

When we read a date time field from a data store such as an API that reads corresponding date time field from a backend SQL database, the format of the date time field is an ISO formatted date. An ISO formatted date is of the form:

YYYY-MM-DD HH:MM:SS.MM 

After our component reads in API data that contains date time fields, the format is confirmed in our debugger:

In a custom formatter, we can use the date library toLocaleDateSting() function to return the date formatted to the desired target locale.

export class DateLocaleConstants
{
    public static EN_US_Language = "en-US";
    public static EN_GB_Language = "en-US";
}

A custom data formatter that converts the date into one of two common date formats:

DDMMYYYY

MMDDYYYY

The routine below takes a date in string format, converts it to a JavaScript date object, then returns it with one of the two common date formats above: 

import { getLocaleDateFormat } from "@angular/common";
import { DateLocaleConstants } from "../reference/dateLocaleConstants";

export class LocalDateFormatter
{
    public static showDateAsDDMMYYYY(value: Date)
    {
        const newDate = new Date(value);
        return newDate.toLocaleDateString(DateLocaleConstants.EN_GB_Language);
    }
    public static showDateAsMMDDYYYY(value: Date)
    {
        const newDate = new Date(value);
        return newDate.toLocaleDateString(DateLocaleConstants.EN_US_Language);
    }
}

After retrieving the formatted date, we display it.

When we use the Chrome browser, the date format is determined by the Browser language as defined In the Chrome Settings:

If we wish to use the browser Language settings, we can use one of the languages defined in the navigator object as shown:

To extract a date and display it in the format we desire, use the custom formatter.

this.useraccount = curruser;  
const dob = new Date(curruser.dob);
this.dobString = LocalDateFormatter.showDateAsDDMMYYYY(dob);

We must also keep in mind the ZERO date. The zero date is:

1000-01-01 0000.00

To detect the zero date or NULL date, we check the year is equal to 1 as shown:

this.hideDate = dob.getFullYear() === 1;

In case, we can hide NULL dates from the user until they are defined.

The HTML to display dates in a read only input is shown:

<div *ngIf="!hideDate" class="form-group">
      <label for="dob">Date of Birth:</label>
      <input readonly [(ngModel)]="dobString" name="dob" 
      		class="form-control col-sm-6" placeholder="Dob" 
      		placement="right" ngbTooltip="Enter DOB">
</div>

In the next section, I will show how to set data in the date picker component.

Setting Data in a Date Picker Component

Below is a material date picker HTML definition that has a predefined date set as the starting date:

<div class="form-group">
    <label for="dob">Date of Birth:</label>
    <br />
    <input matInput [matDatepicker]="picker" name="dob" 
        [(ngModel)]="useraccount.dob"
        (dateInput)="addEvent('input', $event)" 
   	    (dateChange)="addEvent('change', $event)">
    	<mat-datepicker-toggle matSuffix [for]="picker">
  	    </mat-datepicker-toggle>
        <mat-datepicker #picker [startAt]="startDate"></mat-datepicker>
</div>

Now suppose that we wish to display an ISO date from an API and would like to display it. The ISO date is in the format:

1978-07-21T10:04:35.251

We then set the date picker start date with a specific date:

this.useraccount = curruser;
this.startDate = curruser.dob;

When the date picker is displayed with this date selected, it will look as shown:

In the next section, I will show how to extract the date properties and the date time value from the date picker component.

Retrieving Date Time and Date Properties from the Date Picker

To be able to retrieve the selected date time from the date picker we create an event handler to the Material Date Picker dateChange event:

(dateChange)="addEvent('change', $event)">

Within the event handler we retrieve the date properties (date, month, and year) from the date value retrieved from the selected date event handler data:

addEvent(type: string, event: MatDatepickerInputEvent<Date>) {
    let selectedDate = new Date();   
    selectedDate.setDate(event.value.getDate());
    selectedDate.setMonth(event.value.getMonth());
    selectedDate.setFullYear(event.value.getFullYear());
    this.dob = selectedDate;
    this.useraccount.dob = this.dob;
    this.startDate = selectedDate;
}

The event hander data is an ISO date with date, month, full year, and day of week:

The date can then be used to reset the start date within the date picker and be available for update back to our API.

You have seen how to interact with and process selected dates within an Angular Material Date Picker component.

Processing the dates requires some basic understanding of the JavaScript date object API methods which can be obtained here on how to retrieve and set date properties. In addition, understanding the basic event handling for the control from the HTML template (as I showed earlier) allows us to retrieve selected dates and set these within date variable within our component. Once we have these in place using the Material Date Picker is quite straightforward.

That is all for today’s post.

I hope you found today’s post useful and informative.

Social media & sharing icons powered by UltimatelySocial