最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Format created_at date in Reactjs - Stack Overflow

programmeradmin1浏览0评论

I have the following

{journal.createdAt}

2019-10-30T14:01:59.689Z

Which is outputting the created_at date.

How do I go about formatting this?

I've given this a shot but I think I have the value in the wrong place

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

I'm getting

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

I have the following

{journal.createdAt}

2019-10-30T14:01:59.689Z

Which is outputting the created_at date.

How do I go about formatting this?

I've given this a shot but I think I have the value in the wrong place

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

I'm getting

RangeError: date value is not finite in DateTimeFormat.format()
Share Improve this question asked Oct 30, 2019 at 23:28 user8331511user8331511
Add a ment  | 

1 Answer 1

Reset to default 6

According to ES2015, Intl.DateTimeFormat.format(date) expects the date parameter to be a number representing the number of milliseconds since epoch. However, in the MDN docs examples and my own testing on recent Firefox, Chrome, and Safari, those browsers will also accept a Date object.

Since the journal.createdAt is presumably an ISO8601-formatted string, you can use Date.parse(journal.createdAt) or new Date(journal.createdAt) and pass the resulting value to Intl.DateTimeFormat.format, although the former is the way to do it according to the specifications.

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>
    );
  }
}
发布评论

评论列表(0)

  1. 暂无评论