在reactjs组件中将日期格式化为长

format date as long inside reactjs component

本文关键字:格式化 日期 reactjs 组件      更新时间:2023-09-26

我有一个类似的组件

var Post = React.createClass({

render: function () {
    return (
      <li key={ this.props.message.uid }>
        <div className="avatar">
          <img src={ this.props.message.user.avatar } className="img-circle"/>
        </div>
        <div className="messages">
          <p>{ this.props.message.content }</p>
          <span className="date">{ "@"+this.props.message.user.login + " • " }</span>
          <span className="date timeago" title={ this.props.message.createdAt }>
            { this.props.message.createdAt }
          </span>
        </div>
      </li>
      )
  }
});

结果发现createdAt是一个类似于1451589259845的字符串,我想格式化日期。我如何在ReactJS上做到这一点?我试着把new Date()放在括号里,但出现了一个错误。

在开始返回之前,只需在JS中以通常的方式进行操作,并在中模板化即可

render: function() {
  var cts = this.props.message.createdAt,
      cdate = (new Date(cts)).toString();
  return (
    ...
    <span ...>{ cdate }</span>
    ...
  );
}

有很多方法可以进行字符串格式化,Date内置了许多方法(如toLocaleStringtoUTCString),或者可以使用moment.js 等专用格式化程序

您只需运行常规的JavaScriptNewDate()。然而,我强烈建议使用momentjs,因为它似乎更符合你想要做的事情

在命令行上执行:

npm install moment --save

然后在您的代码中var moment = require("moment");import moment from "moment";取决于您是否使用ES6。

之后,我会这样运行代码。

var timeAgo = moment(this.props.message.createdAt).fromNow()

<span className="date timeago" title={ timeAgo }> { timeAgo }</span>

此外,安装一个包来实现这一点似乎是一个巨大的痛苦,但这一刻真的很好,我强烈推荐它。我推荐它的原因是它人性化了次。例如,fromNow()格式使其表示30秒前、4天前或3个月前。它听起来像是一个人写的,除非指定,否则不会显示大量不必要的信息。我的意思是,如果是几个小时前,大多数人都不想知道是多少分几秒前。因此,出于这些原因,我推荐了这个图书馆。如果你喜欢的话,可以随意使用香草JS,我只是发现这一时刻对于表示来说非常好,让我避免了写大量的数学函数来显示月份等。

想要这种格式吗?

2018年5月30日,星期三`

只需申报

const DATE_OPTIONS = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' };

然后在你的React JS代码中

{(new Date()).toLocaleDateString('en-US', DATE_OPTIONS)}

toLocaleDateString()方法返回一个字符串,该字符串具有该日期的日期部分的语言敏感表示形式

来源和更多选项

您可以使用Intl.DateTimeFormat来控制时间格式。Intl.DateTimeFormat对象是启用语言敏感日期和时间格式的对象的构造函数。

       <span className="date timeago" title={ this.props.message.createdAt }>
            {new Intl.DateTimeFormat('en-GB', { 
                month: 'long', 
                day: '2-digit',
                year: 'numeric', 
            }).format(new Date(this.props.message.createdAt))}
      </span>

它将产生一个示例:"2019年12月17日"格式。

在没有moment.JS 的纯JS中

    const dateFromData= "06/15/1990" //string type
    const formatDate = (dateString: string) => {
    const options: Intl.DateTimeFormatOptions = { //Typescript ways of adding the type
      year: "numeric",
      month: "long",
      day: "numeric",
    };
      return new Date(dateString).toLocaleDateString([], options);
    };
    console.log(formatDate(dateFromData)); // output will be: June 15, 1990

只是一个后续,你的所有答案都是正确的,但我遵循这段代码。在使用Moment将日期传递到我的数组之前,我可以格式化日期吗。但一开始只给了我一个undefined value

const data = upcomingWork.map(u => ({
  id: u.id,
  title: u.title,
  start: Moment(u.created_at.format('yyyy mm dd hh m')),
  end: u.created_at,
}));