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
use dateadapter from core
import { DateAdapter } from '@angular/material/core';
constructor(private dateAdapter: DateAdapter<Date>) {
this.dateAdapter.setLocale('en-GB'); //dd/MM/yyyy
}
`
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>
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');
}
If you want to change the MaterialDatePicker date format into yyyy-mm-dd then use the below code. This code is working for me.
MaterialDatePicker<Long> materialDatePicker=materialDateBuilder.build();
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Long>() {
@Override
public void onPositiveButtonClick(Long selection) {
// Get the offset from our timezone and UTC.
TimeZone timeZoneUTC = TimeZone.getDefault();
// It will be negative, so that's the -1
int offsetFromUTC = timeZoneUTC.getOffset(new Date().getTime()) * -1;
// Create a date format, then a date object with our offset
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
Date date = new Date(selection + offsetFromUTC);
mEt_last_date_to_apply.setText(simpleFormat.format(date));
}
});
mEt_last_date_to_apply is my EditText
I got it working after combining some knowledge from various answers here, so I thought I'd consolidate what worked for me.
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.
formatDate(Date(), "yyyy-MM-dd", 'en-GB')