RKM
RKM

Reputation: 89

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

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!!

Upvotes: 0

Views: 1770

Answers (2)

Jai
Jai

Reputation: 74738

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'"   

Upvotes: 1

Kedar9444
Kedar9444

Reputation: 1843

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

Upvotes: 0

Related Questions