【问题标题】:A javascript function returns different results in Chrome and Firefoxjavascript 函数在 Chrome 和 Firefox 中返回不同的结果
【发布时间】:2021-05-31 19:35:32
【问题描述】:

我在 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 开发工具中运行它,它会返回所需的结果:"5-Feb-2021"

但在 Mozilla Firefox 中,相同的操作会返回:"1-Feb--2021"

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

【问题讨论】:

标签: javascript reactjs firefox ecmascript-6 google-chrome-devtools


【解决方案1】:

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

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

MDN explains and warns 关于这个:

隐式调用:

new Date(dateString)

[...]

如果字符串不符合标准格式,则函数可能会退回到任何特定于实现的启发式或特定于实现的解析算法。

因此,您需要提供 ISO 格式的字符串,或者(更好)调用 Date 构造函数,为日期/时间的每个组成部分提供单独的数值。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2020-03-20
      • 2017-11-10
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多