javascript 函数 returns 在 Chrome 和 Firefox 中的不同结果

A javascript function returns different results in Chrome and Firefox

我在 React 中使用 Date 时发现了一个非常有趣的问题。

函数如下:

  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}`;
  };

它接收一个日期作为参数,在我的例子中,orderDate = "05-Feb-2021 06:29:33 PM";

如果你在 Chrome 开发工具中 运行 这个,它 returns 想要的结果:"5-Feb-2021"

但是在Mozilla Firefox中,同样的操作returns这个:"1-Feb--2021"

为什么会发生这种情况,如何避免?

Firefox 不喜欢 dateString 中的 -。

使用正则表达式将所有出现的 - 替换为 /,然后将字符串转换为 Date 对象。

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}`;
};

旁注:您提供给新日期的参数应该是数字,而不是字符串。尽管日期构造函数会为您强制执行,但最好不要依赖它。

Why is this happening and how can it be avoided?

发生这种情况是因为它留给了代理如何解析非 ISO 字符串。这在语言规范中没有定义。

MDN explains and warns 关于这个:

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.

因此,要么您需要提供 ISO 格式的字符串,要么(更好)您使用 date/time.[=15= 的每个组件的单独数值调用 Date 构造函数]