Angular Material and HTML5 dates, date-time picker / calendar formats and manipulation


 Nowadays Date-time format manipulation of the calendar is very important for any application or a web application so angular is no exception.
So In this article, we are looking into different types of date/time pickers.
As technology advanced html5 itself provides a lot of date formats and calendar types but those are not much interactive and as we are looking into angular, angular material also provides many formats for date and time. But angular material doesn’t provide combined date-time picker, so we are using owl-date-time and we need to install the same
[You can get a link to download the project at bottom of the page]
[ If you are preparing for an interview please click here - angular interview questions and answers ]



Following is the command, ng-pick-datetime.  

PS D:\Angular-DemoApps\Angular 8 - Material Date and HTML5 Date formats and manipulation> npm install ng-pick-datetime --save
npm WARN bootstrap@4.3.1 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.       
npm WARN bootstrap@4.3.1 requires a peer of popper.js@^1.14.7 but none is installed. You must install peer dependencies yourself.     
npm WARN ng-pick-datetime@7.0.0 requires a peer of @angular/cdk@^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ ng-pick-datetime@7.0.0
added 1 package from 1 contributor in 49.472s


After installation, we have created two sections in our HTML page, in the first section we are showing how html5 is capable to use different calendars or date picker or date-time pickers and in the second section we are showing angular-materials date pickers and date-time pickers or calendars doing the same with interactive design.

<div class="container">
  <br>
  <div class="row">
    <div class="col-12 text-center">
      <h4>materia Date and Html5 date pickers and Formats manupulation in Angular</h4>
    </div>
  </div>
  <hr>
  <div class="row">
    <div class="col-6">
      <h4>Date picker and format manupulation in HTML5</h4>
      <hr>
      <div class="form-group">
        <label class="col-6 form-control-sm" for="date"> simple plane date</label>
        <input class="col-6 form-control-sm" type="date">
      </div>
      <div class="form-group">
        <label class="col-6 form-control-sm" for="date"> date with min - max </label>
        <input class="col-6 form-control-sm" type="date" min="2018-01-01" max="2019-12-31">
      </div>
      <div class="form-group">
        <label class="col-6 form-control-sm" for="date"> moth picker</label>
        <input class="col-6 form-control-sm" type="month">
      </div>
      <div class="form-group">
        <label class="col-6 form-control-sm" for="date"> Date And Time</label>
        <input class="col-6 form-control-sm" type="datetime-local">
      </div>
    </div>
    <div class="col-6">
      <h4>Date picker Formats manupulation in Angular</h4>
      <hr>
      <div class="form-group">
        <label class="col-6 form-control-sm" for="date"> simple plane date</label>
        <input matInput [matDatepicker]="date1">
        <mat-datepicker-toggle matSuffix [for]="date1"></mat-datepicker-toggle>
        <mat-datepicker #date1 startView="multi-year"></mat-datepicker>
      </div>
      <div class="form-group">
        <label class="col-6 form-control-sm" for="date"> date with min - max</label>
        <input matInput [matDatepicker]="date2" [min]="minDate" [max]="maxDate">
        <mat-datepicker-toggle matSuffix [for]="date2"></mat-datepicker-toggle>
        <mat-datepicker #date2 startView="multi-year"></mat-datepicker>
      </div>
      <div class="form-group">
        <label class="col-6 form-control-sm" for="date"> month picker</label>
        <input matInput [matDatepicker]="date3">
        <mat-datepicker-toggle matSuffix [for]="date3"></mat-datepicker-toggle>
        <mat-datepicker #date3 startView="multi-year" (monthSelected)="chosenMonthHandler($event, date3, tmpDate)">
        </mat-datepicker>
      </div>
      <div class="form-group">
        <label class="col-6 form-control-sm" for="date"> Date and time picker</label>
        <input style="width:170px" [owlDateTime]="dttm">
        <mat-datepicker-toggle matSuffix [owlDateTimeTrigger]="dttm"></mat-datepicker-toggle>
        <owl-date-time #dttm></owl-date-time>
      </div>
    </div>
  </div>
  <hr>
</div>



In above code we used simple date picker, date picker with min-max range, moth picker, and date-time picker.


Following is the typescript file for the above HTML, where we have defined different formats for material calendar.

import { Component } from '@angular/core';
import { MatDatepicker } from '@angular/material/datepicker';
import { MAT_DATE_FORMATSDateAdapter } from '@angular/material/core';
import { MyDateAdapter } from './date-utility/MyDateAdapter';

export const SIMPLE_FORMATS = {
  parse: {
    dateInput: 'DD/MM/YYYY',
  },
  display: {
    dateInput: 'DD/MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

export const MONTH_FORMATS = {
  parse: {
    dateInput: 'MM/YYYY',
  },
  display: {
    dateInput: 'MMM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [
    {
      provide: DateAdapter,
      useClass: MyDateAdapter // this is optional, if we need some user        //                               defined format
    },
    {
      provide: MAT_DATE_FORMATS,
      useValue: SIMPLE_FORMATS
      // useValue: MONTH_FORMATS

    },
  ],
})

export class AppComponent {
  title = 'DemoProjAng8';
  tmpDate: { valueDate } = { value: new Date() };
  minDate = new Date('01/12/2019');
  maxDate = new Date('12/12/2019');

  constructor() { }

  chosenYearHandler(normalizedYearanytmpDate) {
    tmpDate.value = new Date(normalizedYear);
  }

  chosenMonthHandler(normalizedMonthanydatepickerMatDatepicker<any>, tmpDate) {
    tmpDate.value.setMonth(normalizedMonth.getMonth());
    datepicker.close();
    datepicker.select(tmpDate.value);
  }
}


In the above code, we have defined different format for material calendar and passed in provider and also we have extended date adapter to create our own date format(it is not necessary to extend default date adapter, extend only when you want your specific date format rather than inbuilt format).
For month picker/calendar we have used chosenMonthHandler() function, which gets called on the selection of the month. In that function, we have accepted the selected date and assigned it to the related calendar and closed the calendar.

Following is the extended date adapter, where we have implemented logic for full month name and year – date format.

import { NativeDateAdapter } from '@angular/material/core';

export class MyDateAdapter extends NativeDateAdapter {
    readonly monthNames = ['January''February''March''April''May''June',
        'July''August''September''October''November''December'
    ];
    // tslint:disable-next-line: ban-types
    format(dateDatedisplayFormatObject): string {
        // tslint:disable-next-line: prefer-const
        let monthWord = this.monthNames[date.getMonth()];
        // tslint:disable-next-line: prefer-const
        let fullYear = date.getFullYear();
        // tslint:disable-next-line: triple-equals
        if (displayFormat == 'MMM/YYYY') {
            return monthWord + ',' + fullYear;
        } else {
            return super.format(datedisplayFormat);
        }
    }
}


Following is the module file where we have imported all the dependencies.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatNativeDateModule } from '@angular/material/core';
import { FormsModule } from '@angular/forms';
import { DatePipe } from '@angular/common';
import { OwlDateTimeModuleOwlNativeDateTimeModule } from 'ng-pick-datetime';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule,
    MatNativeDateModule,
    OwlDateTimeModule,
    OwlNativeDateTimeModule
  ],
  providers: [DatePipe],
  bootstrap: [AppComponent]
})
export class AppModule { }


Here is the Output 





And that’s it, 
I hope you like it.

Here is the link to download the project [click to download ]

Comments