I need help. 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 da
create a file date.adapter.ts
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'},
}
}
app.module.ts
providers: [
DatePipe,
{
provide: DateAdapter, useClass: AppDateAdapter
},
{
provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
}
]
app.component.ts
import { FormControl } from '@angular/forms';
import { DatePipe } from '@angular/common';
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html',
styleUrls: ['datepicker-overview-example.css'],
providers: [
DatePipe,
{
provide: DateAdapter, useClass: AppDateAdapter
},
{
provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
}
]
})
export class DatepickerOverviewExample {
day = new Date();
public date;
constructor(private datePipe: DatePipe){
console.log("anh "," " +datePipe.transform(this.day.setDate(this.day.getDate()+7)));
this.date = new FormControl(this.datePipe.transform(this.day.setDate(this.day.getDate()+7)));
console.log("anht",' ' +new Date());
}
}
app.component.html