2

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 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

working...thank you...how can add default date in date picker
as you can see in return you can change the return format to before .
0

you can use moment.js to change date format.

var moment = require('moment');

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.