Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  144] [ 6]  / answers: 1 / hits: 117537  / 7 Years ago, fri, june 9, 2017, 12:00:00

I don't know how to change the date format of the material 2 datepicker. I've read documentation but I don't understand what I actually need to do. Output date format which datepicker provides by default is f.e.: 6/9/2017


What I'm trying to achieve is to change format to one like 9-Jun-2017 or any other.


Documentation https://material.angular.io/components/component/datepicker doesn't help me at all.


More From » angular

 Answers
22

Here is the only solution I found for this one:



First, create const:



const MY_DATE_FORMATS = {
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
// dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
dateInput: 'input',
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
};


Then you have to extend NativeDateADapter:



export class MyDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat == input) {
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year;
} else {
return date.toDateString();
}
}

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


In format function, you can choose whatever format you want



And the last step, you have to add it into module providers:



providers: [
{provide: DateAdapter, useClass: MyDateAdapter},
{provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS},
],


And that's it. I can not believe that there is no some easy way to change date format through the @Input but let's hope it will be implemented in some future version of material 2 (currently beta 6).


[#57512] Wednesday, June 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
grayson

Total Points: 36
Total Questions: 113
Total Answers: 95

Location: Tonga
Member since Fri, Aug 21, 2020
4 Years ago
grayson questions
;