Varun Sukheja
Varun Sukheja

Reputation: 6548

Angular8: Global date format config

I am using Angular8 and want to format date and time but I have to use date pipe with same format pattern again and again as shown below

<p>{{ myDate | date: 'dd MMM yyyy, h:mm a' }}</p>
<p>{{ myOtherDate date: 'dd MMM yyyy, h:mm a' }}</p>
<p>{{ otherVar }}</p>
<p>{{ myOtherOtherDate date: 'dd MMM yyyy, h:mm a' }}</p>

and same format date: 'dd MMM yyyy, h:mm a' is to be used in each and every component of my project.

Is there a way where I can provide a global config in the providers of my App Module, something like this

@NgModule({
    providers: [
        {provide: LOCAL_PIPE_DATE_PATTERN, useValue: 'ddMMyy'},
    ],
})
export class AppModule {}

and just use the date pipe as

<p>{{ myDate | date }}</p>
<p>{{ myOtherDate | date }}</p>
<p>{{ otherVar }}</p>
<p>{{ myOtherOtherDate | date:'MMyyDD' }}</p> (If format changed)

Upvotes: 1

Views: 3493

Answers (2)

Miguel Pinto
Miguel Pinto

Reputation: 563

You could create a new date pipe in your project and initialize always the format

@Pipe({
    name: "myDate"
})
export class MyDatePipe {

    constructor(private datePipe: DatePipe) {}

    transform(value: any): string {
        let format = "dd MMM yyyy, h:mm a";
        return this.datePipe.transform(new Date(value), format);
    }
}

Upvotes: 0

Supporterino
Supporterino

Reputation: 181

You could create a local DatePipe in your ts file and convert the date in the Format you use the most and the rest of the time use the Pipeline it self.

    yourNormalDateString : Date = new Date();
    datePipe = new DatePipe('YOUR_LOCAL_CODE');
    dateToDisplay = this.datePipe.transform(this.yourNormalDateString, 'Your Date Format String');

Upvotes: 0

Related Questions