React: date and date format in api preview and console of that api response are showing different

35 Views Asked by At

I have React-Node application. I am calling one node api which giving me correct datetime format in Developer's Network tab's preview. But when I console that api response, I am getting datetime in Local format.

Preview of api - Note eventStartDate format

enter image description here

Console of api response - Note eventStartDate format

enter image description here

I am not getting why those date are coming in different format and are not matching though api is same in Network and console.

What will be the cause of this?

Please guide and help. Thanks.

1

There are 1 best solutions below

2
Matt Johnson-Pint On

Your API returns JSON with a string containing a UTC-based ISO8601/RFC3339 timestamp:

"eventStartDate":"2024-03-18T03:30:00.000Z"

That's perfect.

You then parse that JSON somewhere in your app code, replacing it with a JavaScript Date object - i.e. new Date(eventStartDate). That's fine too. (Possibly this is done automatically by your framework/library code.)

Internally to the Date object, the corresponding timestamp of 1710732600000 is stored. That's the only value encapsulated by the Date object.

Then later, you are displaying the object in the console. The browser you're running (Chrome, etc.) is choosing to display the local-time equivalent of that timestamp - as if you called toString() on the Date object. That's why you see:

eventStartDate: Sun Mar 17 2024 09:00:00 GMT-0400 (Eastern Daylight Time)

Note that Eastern Time comes from your computer - not anything stored in value or in the Date object itself. If I did the same thing in another time zone, I'd see a different local value representing the same instant in time.

This is just how the Date object works.

You said you needed the UTC time, and I presume in the same ISO8601/RFC3339 format, so call eventStartDate.toISOString().