Angular - DatePipe not recognizing date format

2k Views Asked by At

In my Angular application, I have to display the date in 'MM/dd/yyyy' format. Web API is returning a date in "2020-12-01T00:00:00" format.

When I use the below line of code, DatePipe not recognizing the date but if I manually modify the date to "2020-12-01T00:00:00.000Z" then DatePipe converting to the expected 'MM/dd/yyyy' format.

let res = this.datePipe.transform(new Date('2020-12-01T00:00:00'),'MM/dd/yyyy');

let res = this.datePipe.transform(new Date('2020-12-01T00:00:00.000Z'),'MM/dd/yyyy');

The first one is not working and the second one is working. But my API returning data in the first format.

Can someone help me to change the date from first to the second format using Typescript?

2

There are 2 best solutions below

0
On
  1. I don't know if your code example was just a simplified version to demonstrate your issue, but if you're using DatePipe in your application, you can just use the formatDate function instead. All DatePipe does is basically a null check and wrapping of the function in a try/catch block.
  2. If you pass a Date object to either the pipe or the function, then the object instance should be used. Therefore if you are having an issue it is the browser failing when trying to parse the date when calling new Date('...'). Try console.log(isNaN(new Date('2020-12-01T00:00:00'))). If the reuslt is true then you know the browser is the culprit.
  3. The pipe or the function can handle strings and uses a regex to parse them. Instead of wrapping the value in a Date object, just pass the string and see what happens then.
let res = this.datePipe.transform('2020-12-01T00:00:00','MM/dd/yyyy');
let res2 = this.datePipe.transform('2020-12-01T00:00:00.000Z','MM/dd/yyyy');
  1. I was not able to recreate your issue using Angular 10 and Chrome on Windows.
0
On

Z means ISO 8601

try:

let res = this.datePipe.Transform(new Date('2020-12-01T00:00:00').toISOString(),'MM/dd/yyyy');