I can't seem to get Material Datepicker to accept the format I'm giving it. I want to format the date as YYYY-MM-DD, but it insists on using M/D/YYYY.
Below is a stack-blitz where I'm reproducing the issue. Additionally, it's putting the previous date selected, at the bottom of the HTML page seemingly unsolicited.
Image of the Stackblitz below:

I am customizing it as indicated by many different tutorials and documentation:
export const MY_DATE_FORMATS = {
parse: {
dateInput: 'YYYY-MM-DD',
},
display: {
dateInput: 'YYYY-MM-DD',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY'
},
};
I am including it in my module.ts file:
providers: [
{provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS}
]
I also tried changing out MatNativeDateModule with NativeDateModule:
imports: [
BrowserModule,
FormsModule,
MatDatepickerModule,
NativeDateModule,
BrowserAnimationsModule],
Below is my Stackblitz URL reproducing the issue: https://stackblitz.com/edit/angular-ivy-bfjsid?file=src/app/app.module.ts
In this example, if I select a date, it's putting it in M/D/YYYY in the Input Box. Additionally it's putting the previous value at the bottom of the page, even though I don't have anything referencing it.
I have also tried to make sure the date format class was being used, by messing it up intentionally, and material complained as I would have hoped.
Can someone please take a look?
Thank you in advance.
You need to add Date Adapter in providers for the format to work.
Install dependency @angular/material-moment-adapter
import { MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
}
STackblitz link: https://stackblitz.com/edit/angular-ivy-w1pdob?file=src%2Fapp%2Fhello.component.ts
You need Angular Material Moment Adapter to format date in datepicker.
Step 1:
npm install @angular/material-moment-adapter
Step 2:
app.module.ts
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE, NativeDateModule } from '@angular/material/core';
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS, MomentDateAdapter } from '@angular/material-moment-adapter';
@NgModule({
imports: [
...
MatDatepickerModule,
NativeDateModule,
],
declarations: [...],
bootstrap: [...],
providers: [
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{ provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS }
]
})
export class AppModule {}
You may add this CSS styling rule in global css to hide .cdk-visually-hidden element if not needed.
.cdk-visually-hidden {
display: none;
}
Sample project in StackBlitz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With