Skip to content

Instantly share code, notes, and snippets.

@benjamincharity
Created August 28, 2018 19:53
Show Gist options
  • Save benjamincharity/46cdcb1155b4945ed95495780c67787e to your computer and use it in GitHub Desktop.
Save benjamincharity/46cdcb1155b4945ed95495780c67787e to your computer and use it in GitHub Desktop.
Custom date adaptor for material
import { NativeDateAdapter } from '@angular/material/core';
export const TS_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'},
},
};
export class TsDateAdapter 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: any): string {
if (displayFormat === 'input') {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return this._to2digit(month) + '-' + this._to2digit(day) + '-' + year;
} else {
return date.toDateString();
}
}
private _to2digit(n: number) {
return ('00' + n).slice(-2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment