Search code examples
javascriptjsonreactjsdate-fns

Why is my json date string Invalid for date-fns?


I know this has been asked before. But reviewing those answers I can't figure it out. I have a Json date string docdate: "2020-10-02T00:00:00" that I am trying to convert to a date for display. I use System.Text.Json to serialize it in the API. I am using date-fns node module:

import { format } from 'date-fns';
...
<td>{format(order.docdate, 'yyyy/MM/dd')}</td>

... gives me this error:

RangeError: Invalid time value
370 | var originalDate = toDate(dirtyDate);
371 | 
372 | if (!isValid(originalDate)) {
373 |   throw new RangeError('Invalid time value');
374 | } // Convert the date in system timezone to the same date in UTC+00:00 timezone.
375 | // This ensures that when UTC functions will be implemented, locales will be compatible with them.
376 | // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376

Why is my date string Invalid?


Solution

  • format from date-fns takes a Date object or a Number, not a string.

    You should first parse the date string with either parse or parseISO from date-fns (giving a Date object), or the built-in Date.parse() giving a number which can be passed to format.