Skip to content

Instantly share code, notes, and snippets.

@harishrathi
Created August 7, 2019 07:48
Show Gist options
  • Save harishrathi/db24a7f1d427a8ca742bd344780680cc to your computer and use it in GitHub Desktop.
Save harishrathi/db24a7f1d427a8ca742bd344780680cc to your computer and use it in GitHub Desktop.
custom-date-adapater.ts
import { Injectable } from '@angular/core';
import { NativeDateAdapter } from '@angular/material';
import { format as formatFns } from 'date-fns';
// https://github.com/angular/components/blob/9eeb4b5aa0473c0815a73bfe3c2ed6164d86a3b3/src/material/core/datetime/native-date-formats.ts
// https://github.com/angular/components/blob/fde980c8ad57a803c7bf6ca0d909cedccc354f06/src/material/core/datetime/native-date-adapter.ts
export const MAT_CUSTOM_DATE_FORMATS = {
parse: {
dateInput: 'yyyy-MM-dd',
},
display: {
dateInput: 'yyyy-MM-dd',
monthYearLabel: { year: 'numeric', month: 'short' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' },
}
};
@Injectable({
providedIn: 'root'
})
export class CustomDateAdapterService extends NativeDateAdapter {
public createDate(year: number, month: number, date: number): Date {
const localDate = super.createDate(year, month, date);
const offset = localDate.getTimezoneOffset() * 60000;
return new Date(localDate.getTime() - offset); // utcDate
}
public format(date: Date, displayFormat: any): string {
if (displayFormat !== MAT_CUSTOM_DATE_FORMATS.display.dateInput) {
return super.format(date, displayFormat);
} else {
return formatFns(date, MAT_CUSTOM_DATE_FORMATS.display.dateInput);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment