0

I've found a very interesting issue while working with Date in React.

Here is the function:

  const formatDate = (orderDate) => {
    const date = new Date(orderDate);
    const day = date.getDay();
    const month = date.toLocaleString('default', { month: 'long' });
    const year = date.getFullYear();

    return `${day}-${month.slice(0, 3)}-${year}`;
  };

it receives a date as parameter, in my case, orderDate = "05-Feb-2021 06:29:33 PM";

If you run this in Chrome dev tools, it returns the desired result: "5-Feb-2021"

But in Mozilla Firefox, the same operation returns this: "1-Feb--2021"

Why is this happening and how can it be avoided?

Jean Pierre
  • 281
  • 8
  • 21
  • Does this answer your question? [Why does Date.parse give incorrect results?](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – CBroe Mar 02 '21 at 09:16

2 Answers2

2

Firefox does not like the - in dateString.

Replace all occurrences of - with / using a regular expression and then convert the string to Date object.

const formatDate = (orderDate) => {
  const date = new Date(orderDate.replace(/-/g, "/"));
  const day = date.getDate();
  const month = date.toLocaleString("default", { month: "long" });
  const year = date.getFullYear();
  return `${day}-${month.slice(0, 3)}-${year}`;
};

Side Note: The arguments you provide to new Date should be numbers, not strings. Although the date constructor will coerce for you, it's best practice not to rely on it.

ganesh deshmukh
  • 314
  • 4
  • 17
2

Why is this happening and how can it be avoided?

This is happening because it is left to the agent how non ISO strings are parsed. This is not defined in the language specification.

MDN explains and warns about this:

Implicit call:

new Date(dateString)

[...]

If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm.

So either you need to provide the string in ISO format, or (better) you call the Date constructor with individual, numerical values for each component of the date/time.

trincot
  • 317,000
  • 35
  • 244
  • 286