Datepicker not displaying date format MM/DD/YYYY angular 4

允我心安 提交于 2019-12-13 20:19:10

问题


In my angular 4 project, I have a datepicker in my html.

In html:

      <mat-form-field class="col-sm-12 nopadding pull-left">
         <input matInput [matDatepicker]="date" placeholder="Please select a date" [(ngModel)]="txtDate">
         <mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
         <mat-datepicker #date></mat-datepicker>
      </mat-form-field>

Im able to select date and convert it into dd/mm/yyyy format in my DB. When i retrieve date im converting it back to MM/DD/YYYY (the format in which my datepicker works) I am getting the value from web api and in console i can see the value is converted correctly and assigned to the ngModel. But its not displaying in the datepicker field

In ts file

 var dateParts = result.Date.split("/");
 var dateObject = new Date(dateParts [2], dateParts [1] - 1, dateParts [0]);
 this.txtDate=moment(dateObject ).format('MM/DD/YYYY'); -- output of this in console is 11/14/2018 (the desired output)

but the same is not displaying in date-picker. can you please help!!


回答1:


I would rather suggest you to create a custom pipe:

[(ngModel)]="txtDate | dateformatter:'MM/DD/YYYY'"   
import {
  Pipe,
  PipeTransform
} from '@angular/core';

@Pipe({ name: 'dateformatter' })
export class DateFormatterPipe implements PipeTransform {
  transform(value: number, dateformat: string): string {
    var dateParts = result.Date.split("/");
    var dateObject = new Date(dateParts [2], dateParts [1] - 1, dateParts [0]);
    return moment(dateObject).format(dateformat.toUpperCase());
  }
}

Or you can take a look into a date pipe:

[(ngModel)]="txtDate | date:'shortDate'"   



回答2:


since there is no minimal reproducible code you have provided i just went through the Angular Material documentation and found that you need to convert the date to ISOString format. here is code from stackbliz



来源:https://stackoverflow.com/questions/53296117/datepicker-not-displaying-date-format-mm-dd-yyyy-angular-4

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