Intl.DateTimeFormat could not parse valid time value

Viewed 1066

In my react app, I tried to format a date string within a <p>...</p> tag like below:

<p>
    {new Intl.DateTimeFormat("en-US", {
        year: "numeric",
        month: "short",
        day: "2-digit"
    }).format(string)}
</p>

An example of string is "2012-10-16T17:57:28.556094Z". This generated RangeError: Invalid time value. However, by converting String into Date, the code below worked.

<p>
    {new Intl.DateTimeFormat("en-US", {
        year: "numeric",
        month: "short",
        day: "2-digit"
    }).format(new Date(string))}
</p>

Shouldn't Intl.DateTimeFormat be able to parse String correctly?

1 Answers

Shouldn't Intl.DateTimeFormat be able to parse String correctly?

No. DateTimeFormat objects don't have a parser. The format method expects the argument to be a Date object (though any value where ToNumber(value) is not NaN "works"), not a string (see ECMA-402).

Related