javascript - 在Reactjs中格式化created_at日期

标签 javascript date

我有以下内容

{journal.createdAt}

2019-10-30T14:01:59.689Z

输出created_at日期。

我该如何格式化它?

我已经尝试过,但我认为我的值(value)放在了错误的地方

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

我懂了

RangeError: date value is not finite in DateTimeFormat.format()

最佳答案

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

journal.createdAt大概是 ISO8601 格式的字符串,您可以使用 Date.parse(journal.createdAt) new Date(journal.createdAt)并将结果值传递给 Intl.DateTimeFormat.format ,虽然前者是按照规范来做的方式。

Working example

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

关于javascript - 在Reactjs中格式化created_at日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58634980/

相关文章:

将 unicode 伪字母转换为常规字符的 JavaScript 函数?

java - (Date) 可以通过将外部可变对象存储到 CategoryModel.createdDate 来公开内部表示

javascript - 无需 Websocket 即可向浏览器异步推送消息

javascript - 在推送对象时,我得到的所有内容都是 NULL angular2+typescript

java - Java 中纪元时间格式的字符串到日期

sql - Access 和 SQL Server 计算日期不同

java - 如何在 Java 中打印日期而不打印时间?

java - java.util.GregorianCalendar 在 1976 年 3 月 28 日到 3 月 29 日之间发生了什么?

javascript - 解决 friend 名字中单引号的错误

javascript - 在 html5 Canvas 中用鼠标旋转图像