I would like to display my Angular Material date picker selected date to display the format as yyyy-mm-dd. I have tried a bunch of methods, successfully changing the date format, but I cannot get it to display the modified date format.
In this method I set both the date as the new format, as well as returning the value in the desired format:
getValidDate(selectedDate) {
const date = new Date(selectedDate);
const dd = String(date.getDate()).padStart(2, '0');
const mm = String(date.getMonth() + 1).padStart(2, '0');
const yyyy = date.getFullYear();
this.model.dob = yyyy + '-' + mm + '-' + dd;
this.dateOfBirth.setValue(yyyy + '-' + mm + '-' + dd);
return yyyy + '-' + mm + '-' + dd;
}
I have also implemented a custom date for MAT_DATE_FORMATS:
providers: [
{
provide: MAT_DATE_FORMATS,
useValue: DATE_FORMATS
}
export const DATE_FORMATS = {
parse: {
dateInput: 'YYYY-MM-DD',
},
display: {
dateInput: 'YYYY-MM-DD',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY'
},
};
This is my HTML:
<mat-form-field
class="example-full-width"
appearance="standard"
matTooltip="Please select date of birth"
matTooltipClass="tooltip-background"
>
<mat-label>Date of birth</mat-label>
<input
matInput
[matDatepicker]="picker"
formControlName="dateOfBirth"
appAutocompleteOff
[max]="maxDate"
(dateChange)=getValidDate(dateOfBirth.value)
[(ngModel)]="model.dob"
/>
<mat-datepicker-toggle
matSuffix
[for]="picker"
></mat-datepicker-toggle>
<mat-datepicker
touchUi
#picker>
</mat-datepicker>
</mat-form-field>
So in essence I am trying to set the date format to display using 3 different methods:
- Via [(ngModel)]
- setValue: this.dateOfBirth.setValue(yyyy + '-' + mm + '-' + dd);
- Via returning the formatted date by calling a method (getValidDate) returning and setting the date format.
I would appreciate any help! :)