Home > database >  Typescrpt - how to convert a json string date representation into a Date object
Typescrpt - how to convert a json string date representation into a Date object

Time:01-01

I have an API call that returns an array of json strings. I need to change the format for the purposes of display - just the month and day is needed.

My logic has a bug because it's translating August as "7" instead of "8". also the day is being interpretted as 3 instead of 25 for the first record.

Sample Json Data

This is a sample of what the data looks like:

[
{"reportRefreshDate":"2021-08-25T07:18:06","Widgets":13,"Gizmos":6},{"reportRefreshDate":"2021-08-28T07:18:06","Widgets":1,"Gizmos":0},{"reportRefreshDate":"2021-08-29T07:18:06","Widgets":1,"Gizmos":0}
]

Code

Here's the relevant code:

  const reportRefreshDate: string[] = [];
  const totalWidgets: number[] = [];
  const totalGizmos: number[] = [];
  const totalDooDads: number[] = [];

  for (const record of data) {
    const tempdate = new Date(record.reportRefreshDate);

    reportRefreshDate.push(tempdate.getMonth()   "/"   tempdate.getDay())
  }

In a debug window, this is what I've tried:

tempdate
Wed Aug 25 2021 07:18:06 GMT-0400 (Eastern Daylight Time)

tempdate.getMonth()
7

If you could point me in the right direction, that'd be great. Right now i'm also looking at the overloads for Date to see if the way I created the variable is incorrect.

EDIT 1

I guess I could just convert to localeDateString and then strip off the year? I'm noticing that when I use the toLocaleDateString() it returns the right values in my debug console:

tempdate.toLocaleDateString()
'8/25/2021'

CodePudding user response:

You shouldn't use getDay() function which will return the day of week as a number starting from 0.

Instead, you should use getDate() function which will return the day of month. So you might need to refactor your code to the following.

reportRefreshDate.push(tempdate.getMonth()   "/"   tempdate.getDate())
  • Related