Skip to content

Instantly share code, notes, and snippets.

@shalaby
Forked from wottpal/date-formats.ts
Created May 28, 2020 21:28
Show Gist options
  • Save shalaby/762cd2a60029641f52ef42b644ec23a2 to your computer and use it in GitHub Desktop.
Save shalaby/762cd2a60029641f52ef42b644ec23a2 to your computer and use it in GitHub Desktop.
Custom DateFormats & DateAdapter for Angular Material MatDatepicker using Day.js
import { Platform } from '@angular/cdk/platform';
import { NativeDateAdapter } from '@angular/material';
import * as dayjs from 'dayjs';
import 'dayjs/locale/de';
import * as customParseFormat from 'dayjs/plugin/customParseFormat';
import * as localizedFormat from 'dayjs/plugin/localizedFormat';
/**
* Custom Date-Formats and Adapter (using https://github.com/iamkun/dayjs)
*/
export const AppDateFormats = {
parse: {
dateInput: 'DD.MM.YYYY',
},
display: {
dateInput: 'DD.MM.YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
}
}
export class AppDateAdapter extends NativeDateAdapter {
constructor(matDateLocale: string, platform: Platform) {
super(matDateLocale, platform)
// Initalize DayJS-Parser
dayjs.locale('de')
dayjs.extend(customParseFormat)
dayjs.extend(localizedFormat)
}
parse(value: any): Date | null {
return dayjs(value, 'DD.MM.YYYY').toDate()
}
format(date: Date, displayFormat: any): string {
return dayjs(date).format(displayFormat)
}
}
/* ... */
/* Adding Providers in a Shared- or App-Module */
@NgModule({
providers: [
{
provide: DateAdapter,
useClass: AppDateAdapter,
deps: [MAT_DATE_LOCALE, Platform]
},
{
provide: MAT_DATE_FORMATS,
useValue: AppDateFormats
}
]
})
export class SharedModule { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment