在Reactjs中格式化created_at日期

5 javascript date

我有以下内容

{journal.createdAt}

2019-10-30T14:01:59.689Z

这是输出created_at日期。

我该如何格式化它?

我已经尝试过,但我认为我的价值用在了错误的地方

{new Intl.DateTimeFormat('en-GB', {
  year: 'numeric',
  month: 'long',
  day: '2-digit'
}).format(journal.createdAt)}
Run Code Online (Sandbox Code Playgroud)

我越来越

RangeError: date value is not finite in DateTimeFormat.format()
Run Code Online (Sandbox Code Playgroud)

Hac*_*ese 6

根据 ES2015,Intl.DateTimeFormat.format(date)期望该date参数是一个数字,表示自纪元以来的毫秒数。然而,在 MDN 文档示例和我自己在最近的 Firefox、Chrome 和 Safari 上进行的测试中,这些浏览器也将接受一个Date对象。

由于journal.createdAt可能是 ISO8601 格式的字符串,因此您可以使用Date.parse(journal.createdAt)ornew Date(journal.createdAt)并将结果值传递给Intl.DateTimeFormat.format,尽管前者是根据规范执行此操作的方法。

工作示例

class App extends React.Component {
  formatter = new Intl.DateTimeFormat("en-GB", {
          year: "numeric",
          month: "long",
          day: "2-digit"
        });

  render() {
    const dateString = "2019-10-30T14:01:59.689Z";

    return (
      <div>
        Using <code>Date.parse</code>: {this.formatter.format(Date.parse(dateString))}
        <br />
        <em>OR</em>
        <br />
        Using <code>new Date</code>: {this.formatter.format(new Date(dateString))}
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)