Why do I get "RangeError: date value is not finite in DateTimeFormat format()" when using Intl.DateTimeFormat in React?

Viewed 10344

I cannot see where the date format is being passed incorrectly to cause the RangeError?

I don't seem to be able to parse user.created. The user details are being brought in from a json response in reality, but I've shown them as a variable in this example.

Here's my MRE:

import * as React from "react";

function Details() {
  const user = {
    firstName: "Anthony",
    created: "2020-08-19T23:13:44.514Z",
    updated: "2020-09-12T00:31:31.275Z"
  };

  const userJoined = new Intl.DateTimeFormat("en-GB", {
    year: "numeric",
    month: "long",
    day: "2-digit"
  }).format(user.created.toString());

  return (
    <div>
      <p>{user.firstName}</p>
      <p>
        Joined:
        {new Intl.DateTimeFormat("en-GB", {
          year: "numeric",
          month: "long",
          day: "2-digit"
        }).format(userJoined)}
      </p>
    </div>
  );
}

export { Details };

Edit nostalgic-dewdney-jrob9

3 Answers

You may need to parse the string to date.

  const user = {
    firstName: "Anthony",
    created: new Date("2020-08-19T23:13:44.514Z"),
    updated: new Date("2020-09-12T00:31:31.275Z")
  };

You get this when you pass an invalid date to format(). Make sure it is a Date().

 import moment from "moment-timezone";   
 moment.utc(date).tz(browserTimezone).format();

I know most of these issues have been resolved in modern versions of browsers, but I just ran into a case where this error was caused by having milliseconds attached to the end of my dates like this --

'2022/10/25 11:22:42.570684', // .570684

This works well in Chrome but not in any other browser i.e. Safari. After removing the milliseconds

'2022/10/25 11:22:42', // Works as expected, no milli seconds.

a link to the docs https://dygraphs.com/date-formats.html

Related