2
votes

I am using material-datepicker for my angular 6 project..By default my date format from material-datepicker is dd-mm-yyyy.But i need yyyy-mm-dd..how can i do this.this is my code

<mat-form-field style="margin-right: 25px;">
    <input matInput [matDatepicker]="picker_start" placeholder="2018-08-31" [(ngModel)]="startdate" >
    <mat-datepicker-toggle matSuffix [for]="picker_start"></mat-datepicker-toggle>
    <mat-datepicker #picker_start></mat-datepicker>
</mat-form-field>
2

2 Answers

2
votes

you can write a simple dateAdapter:

    import { NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS, MatDateFormats } from "@angular/material";


export class AppDateAdapter extends NativeDateAdapter {

    parse(value: any): Date | null {
        if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
          const str = value.split('/');
          const year = Number(str[2]);
          const month = Number(str[1]) - 1;
          const date = Number(str[0]);
          return new Date(year, month, date);
        }
        const timestamp = typeof value === 'number' ? value : Date.parse(value);
        return isNaN(timestamp) ? null : new Date(timestamp);
      }
   format(date: Date, displayFormat: string): string {
       if (displayFormat == "input") {
          let day = date.getDate();
          let month = date.getMonth() + 1;
          let year = date.getFullYear();
          return   year + '-' + this._to2digit(month) + '-' + this._to2digit(day)   ;
       } else if (displayFormat == "inputMonth") {
          let month = date.getMonth() + 1;
          let year = date.getFullYear();
          return  year + '-' + this._to2digit(month);
       } else {
           return date.toDateString();
       }
   }

   private _to2digit(n: number) {
       return ('00' + n).slice(-2);
   } 
}

export const APP_DATE_FORMATS =
{
   parse: {
       dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
   },
   display: {
       dateInput: 'input',
       monthYearLabel: 'inputMonth',
       dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
       monthYearA11yLabel: {year: 'numeric', month: 'long'},
   }
}

DEMO

0
votes

you can use moment.js to change date format.

var moment = require('moment');

var newDate=moment(date).format('YYYY-MM-DD');