0

I want to display the date for each entry (date, text, question, answer) in a json database within a lit element in a js module.

Relevant code:

import { formatWithOptions } from "date-fns/fp";
import compose from "crocks/helpers/compose";

...

const newDate = (x) => new Date(x);


const formatDateWithOptions = formatWithOptions(
  {
    awareOfUnicodeTokens: true,
  },
  "d MMMM, yyyy, h:mm a"
);

const prettyDate = compose(formatDateWithOptions, newDate); // this is registering as an invalid date

When ${prettyDate(date)} is called inside a lit element, it throws

RangeError: Invalid time value.

The date format for (date) inside the json db is valid. Example: "2021-12-24T21:06:06.773Z"

According to the date-fns docs, formatWithOptions() should be fine to call with "d MMMM, yyyy, h:mm a". This post deals with the same error, but is using a different function (formatDistanceToNow). Where am I going wrong with my variables?

WhooNo
  • 911
  • 2
  • 12
  • 28
  • You haven't shown what `date` is in `${prettyDate(date)}`, but clearly it's not in a format that the `Date` constructor can parse. – T.J. Crowder Dec 27 '21 at 19:00
  • @T.J.Crowder just clarified, (date) is in standard format ie "2021-12-24T21:00:47.217Z" – WhooNo Dec 27 '21 at 19:17
  • That's strange, because "Invalid time value" pretty clearly says that the `Date` object's time value (the underlying milliseconds-since-the-Epoch) is invalid (for instance, `NaN`), which happens when you ask `new Date` to parse something it doesn't understand. I suggest reformatting `newDate` to something like `const newDate = (x) => { const dt = new Date(x); return dt; };` and putting a breakpoint on the `return dt;` statement with the condition `isNaN(+dt);`. When the breakpoint trips, look at what `x` is. I suspect you'll find that it's not the format you're expecting. Good luck! – T.J. Crowder Dec 28 '21 at 10:28

0 Answers0