问题
I'm setting up a mat-datepicker for DOB and traditionally the display format is MM/DD/YYYY,I need to change it to DD/MM/YYYY with less coding
I tried format tag in mat-date picker but it does not work,other date pickers like ngbDatepicker format can easily changed through one line of coding
<div class="col-md-3 Dinline-block">
<mat-form-field>
<input matInput [matDatepicker]="picker2" [max]="currentDate"
placeholder="DOB(DD/MM/YYYY)" required formControlName="dob"
readonly />
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-
toggle>
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
</div>
The date displayed after selecting from mat-date picker should be DD-MM-YYYY and when the retrieving the value from date picker it should also be in DD-MM-YYYY format
回答1:
The easiest way is to change the locale:
Add the following to the providers section of your module:
{ provide: MAT_DATE_LOCALE, useValue: 'en-GB' }
回答2:
First, bind the format to your mat-datepicker.
export const MY_FORMATS = {
parse: {
dateInput: 'LL'
},
display: {
dateInput: 'YYYY-MM-DD',
monthYearLabel: 'YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'YYYY'
}
};
along with this you need to import and provide the modules.
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material';
import { MomentDateModule, MomentDateAdapter } from '@angular/material-moment-adapter';
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }
And in HTML follow this simply.
<mat-form-field>
<input
matInput
[matDatepicker]="dp"
placeholder="Verbose datepicker
[formControl]="date"
>
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp></mat-datepicker>
</mat-form-field>
回答3:
Try this in the component you are using mat-datepicker
import { DateAdapter } from '@angular/material';
constructor(private dateAdapter: DateAdapter<Date>) {
this.dateAdapter.setLocale('your locale');
}
回答4:
use dateadapter from core
import { DateAdapter } from '@angular/material/core';
constructor(private dateAdapter: DateAdapter<Date>) {
this.dateAdapter.setLocale('en-GB'); //dd/MM/yyyy
}
`
回答5:
I got it working after combining some knowledge from various answers here, so I thought I'd consolidate what worked for me.
Angular 10:
In your module, import MAT_DATE_LOCALE and add it to providers:
import { MAT_DATE_LOCALE } from '@angular/material/core'
@NgModule({
declarations: [...],
imports: [...],
exports: [...],
providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'en-GB' }
]
})
If you use a shared module to import material this will change all the formats of your datepickers across the site.
回答6:
add to the providers list:
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
回答7:
formatDate(Date(), "yyyy-MM-dd", 'en-GB')
来源:https://stackoverflow.com/questions/55721254/how-to-change-mat-datepicker-date-format-to-dd-mm-yyyy-in-simplest-way