Date-fns is returning incorrect dates

I have a collection of date strings stored in a database in this format:

2018-06-28T14:06:26.524Z

2018-07-02T10:32:18.818Z

2018-07-06T15:08:50.233Z

I need to convert these dates into a format like this on the frontend:

28 June 2018 14:06:26

02 July 2018 10:32:18

06 July 2018 08:50:23

My attempt at doing this using an npm package called date-fns is:

format(new Date(date).toISOString(), 'dd MMMM yyyy HH:MM:ss');

The problem is that the dates returned from the above are incorrect:

2018-06-28T14:06:26.524Z returns 28 June 2018 15:06:26

2018-07-02T10:32:18.818Z returns 02 July 2018 11:07:18

2018-07-06T15:08:50.233Z returns 06 July 2018 16:07:50

What am I doing wrong here and how to I fix this so the dates are returned correctly?

new Date attaches time zone information, so when you put that date into the constructor, it’s going to add on local TZ info. From the looks of things it’s adding daylight savings. Use the parse function from date-fns rather than new Date, that should work afaics from looking at people having similar issues:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.