Saturday, 26 August 2023

handle dates properly with different timezones in a React App

I have a react application that stores and retrieves datetimes, then disable the unavalaible dates and times.

When the dates are saved from a calendar into the Database, they are one hour late.

When I retrieve the dates from the database, they are 2 hours late.

Imagine I have chosen this dateTime from the calendar : 24 Aug 2023 at 21:30

In the database it is saved as : 2023-08-24 20:30:00.000

When I retrieve it I get : 2023-08-24T19:30:00.000Z

When I wrap it in a Date object I get: Date Thu Aug 24 2023 20:30:00 GMT+0100 (UTC+01:00).

console.log(res.data[0].dateTime) // 2023-08-24T19:30:00.000Z
console.log(new Date(res.data[0].dateTime)) //Date Thu Aug 24 2023 20:30:00 GMT+0100 (UTC+01:00)

When I display it using date-fns I get 20:30 instead of 21:30

<td className="border border-neutral-500 p-3">
        {format(new Date(res.data[0].dateTime), 'kk:mm')}
</td>

Note that when I deployed this app on LWS which has a different timezone, the dates are 2 hours late, and I cannot update the system timezone.

Please help me understand how can I handle these dates properly with different timezones in order to have the same date and times.



from handle dates properly with different timezones in a React App

No comments:

Post a Comment