0

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?

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
Tech Learner
  • 1,227
  • 6
  • 24
  • 59
  • Interesting. I do not have the same results. What browser are using? Also, how are you initializing the DatePipe? – Daniel Gimenez Nov 19 '20 at 17:58
  • @DanielGimenez - I am using Chrome browser. Can you please help me to convert the format from '2020-12-01T00:00:00' to '2020-12-01T00:00:00.000Z'. – Tech Learner Nov 19 '20 at 18:04
  • From Angular 9 you can use directly the function `formatDate`: https://angular.io/api/common/formatDate (datepipe use this function internally) – Eliseo Nov 20 '20 at 07:45

2 Answers2

1
  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.
Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70
1

Z means ISO 8601

try:

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

AmenzO
  • 409
  • 7
  • 19