Cannot Instantiate DatePipe

If you take a look at source code then you will see that DatePipe constructor asks for a required parameter:

constructor(@Inject(LOCALE_ID) private _locale: string) {}

There is no default locale for DataPipe

https://github.com/angular/angular/blob/2.0.0/modules/%40angular/common/src/pipes/date_pipe.ts#L97

That’s why typescript gives the error.
This way you have to initiate your variable as shown below:

datePipeEn: DatePipe = new DatePipe('en-US')
datePipeFr: DatePipe = new DatePipe('fr-FR')
constructor() {
  console.log(this.datePipeEn.transform(new Date(), 'dd MMMM')); // 21 September
  console.log(this.datePipeFr.transform(new Date(), 'dd MMMM')); // 21 septembre
}

Hope it helps you!

Leave a Comment