Search code examples
javascriptangulartypescriptangular-materialangular5

How to I get current time from angular material Date picker?


I am using angular material datepicker https://material.angular.io/components/select/overview

but this returns only the date and not the current time : Mon May 28 2018 00:00:00 GMT+0530 (IST)

Is there any way I can get the current time also from this?


Solution

  • You can use the ngModelChange to parse the date before setting it to your model, I recommend you momentJS for easy date manipulations.

    in the HTML

     <input [ngModel]="date" (ngModelChange)="onDataChange($event)"  matInput [matDatepicker]="picker" placeholder="Choose a date">
    

    In your Component.ts

      onDataChange(newdate) {
        const _ = moment();
        const date = moment(newdate).add({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
        this.date = date.toDate();
        console.log({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
      }
    

    you can find the full solution here https://stackblitz.com/edit/angular-ecq2lc