1

I am using React, and receiving the following data in Typescript. I want to display date in this format. mm/dd/yyyy,

export type Payment = {
  paymentId: number;
  paymentDate: Date;
} 

Data looks like this example: 2022-02-11T20:00:00.000Z

I cannot do this, as it gives error: date .toISOString is not a function

{payment.paymentDate.toISOString().substring(0, 10)}

I have to reconvert into Date again to show. All my dates are valid in checking data, so why do I need to reconvert again?

{new Date(payment.paymentDate).toISOString().substring(0, 10)}
mattsmith5
  • 540
  • 4
  • 29
  • 67

1 Answers1

1

Seems like your paymentDate isn't really a JavaScript Date, but a `string.

string doesn't have toIsoString method

TypeScript is only a build time tool, it can't enforce data type.

I would use a library like date-fns for example, but other than that, you can use Where can I find documentation on formatting a date in JavaScript?

mattsmith5
  • 540
  • 4
  • 29
  • 67
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • hi Konrad, just learning that, how come my Typescript isn't enforcing data coming through api, and how would I convert to mm/dd/yyyy ? – mattsmith5 Aug 07 '22 at 18:11
  • TypeScript is only a build time tool, it can't enforce data type – Konrad Aug 07 '22 at 18:13
  • ok I see, how would I convert to date then? is this correct? new Date(payment.paymentDate).toISOString().substring(0, 10) – mattsmith5 Aug 07 '22 at 18:13
  • I would use a library like `date-fns` for example, but other than that https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript – Konrad Aug 07 '22 at 18:14
  • You can also check `zod` for data validation – Konrad Aug 08 '22 at 08:34