Skip to content
Advertisement

Change format of date displayed in Datepicker (Angular) using custom pipe

By default the datepicker is using MM/dd/yyyy format and i want it to be set according to the browser language e.g.) if English India then it should be dd/MM/yyyy(used in the example below)

This is my custom datepipe ->

@Pipe({ name: 'replaceDate1' })
export class ReplaceDate1Pipe implements PipeTransform {
    transform(value: string): string {
        if (!value) {
            return value;
        }

        let date1 = (new Date(value));
        var userLang = navigator.language;  
        console.log(value);
        console.log(date1);
        console.log(Intl.DateTimeFormat(userLang).format(date1));
        return Intl.DateTimeFormat(userLang).format(date1);
    }
}

This is the html part ->

<mat-form-field [floatLabel]="never" appearance="fill" id="xxx" class="textbox1" panelClass="option-panel">
<mat-label>Choose a date</mat-label>
<input [min]="todayDate" [disabled]="fun1()" readonly matInput [matDatepicker]="picker" [value]="program.datetobeformatted | replaceDate1" [matDatepickerFilter]="myDateFilter" (dateChange)="onChange($event, 'xxx',  program, $index)">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Here i want to change the format of the date value shown in the date of datepicker, but the value is displayed as empty field in UI Empty datepicker value image

i logged the values when the pipe is called and it is satisfactory but why it is not shown in the datepicker

and is there any way to change the datepicker format from HTML file (I just want to display the format accordingly and not alter the value of date format used for backend services)

these are the log outputs from the replaceDate1 pipe

2021-06-30T00:00:00Z
Wed Jun 30 2021 05:30:00 GMT+0530 (India Standard Time)
30/6/2021

Advertisement

Answer

Have you tried changing the locale for the Mat Date Picker?

{ provide: MAT_DATE_LOCALE, useValue: 'en-IN' }

Add that to the providers section of your module

https://material.angular.io/components/datepicker/overview

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement