Reputation: 1972
My api backend needs a date with the format: dd/MM/YYYY. I change the input format datepicker in dd/MM/YYYY.
Example: 05/01/1992(input) gives Sun Jan 05 1992 00:00:00 GMT+0100 (CET) {} in console
My customInputFormatDatepicker
import { NativeDateAdapter } from '@angular/material';
export const APP_DATE_FORMATS = {
parse: {
dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
},
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'numeric' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' },
}
};
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: Object): string {
if (displayFormat === 'input') {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year;
} else {
return date.toDateString();
}
}
private _to2digit(n: number) {
return ('00' + n).slice(-2);
}
}
Upvotes: 0
Views: 939
Reputation: 400
it looks like your format function's else statement is always running. not so sure that displayFormat will === 'input'
, for me it wasn't. what you could do in the format method is pass your own format using moment.js like so:
const formatString = '<your-format>';
return moment(date).format(formatString);
did you add the providers to ngModule
providers: [
{ provide: DateAdapter, useClass: DateFormat },
{ provide: MAT_DATE_FORMATS, useValue: MOMENT_DATE_FORMATS }
],
also, this worked for me for the date formats.
const APP_DATE_FORMATS = {
parse: {
dateInput: 'd/MM/yyyy'
},
display: {
dateInput: 'dd/MM/YYYY',
monthYearLabel: 'MMMM Y',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM Y'
}
};
Upvotes: 1