How to customize date in <mat-datepicker> to 2017-11-20T11:23:00 - Angular material 5

此生再无相见时 提交于 2019-12-20 06:09:27

问题


I am using following code for displaying date picker

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
 </mat-form-field>

but it is returning result as Wed Jan 24 2018 00:00:00 GMT+0530 (India Standard Time) but I need it as 2018-01-24T11:23:00. Could you please help me here?

Thank you.


回答1:


In your component.html, use two inputs, first one to hold date from mat-datepicker, second one bind with model. In (selectedChanged) event of the 'mat-datepicker' update 'myModel.MyDateString' from the date-picker value:

<mat-form-field>
    <input type="hidden" [matDatepicker]="myDate">
    <input  matInput  placeholder="My date" [(ngModel)]="myModel.MyDateString">
    <mat-datepicker-toggle matSuffix [for]="myDate"></mat-datepicker-toggle>
    <mat-datepicker #myDate  (selectedChanged)="updateDateToString($event)"></mat-datepicker>
  </mat-form-field>

Inside your component.ts:

updateDateToString(event) {
let newDate = new Date(event)

let dd: number | string = newDate.getDate();
if (dd < 10) {
  dd = '0' + dd;
}
let mm: number | string = newDate.getMonth() + 1;
if (mm < 10) {
  mm = '0' + mm;
}
const yy: number = newDate.getFullYear();
this.myModel.MyDateString = `${yy}-${mm}-${dd}`;    

}




回答2:


Convert the value to JSON. The toString output converts to the format "Wed Jan 24 2018 00:00:00 GMT+0530". When you convert it to JSON it is formatted as 2018-01-24T11:23:00.000Z



来源:https://stackoverflow.com/questions/48396025/how-to-customize-date-in-mat-datepicker-to-2017-11-20t112300-angular-mater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!