Javascript 在 reactjs 组件中格式化日期一样长

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34550738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:32:27  来源:igfitidea点击:

format date as long inside reactjs component

javascriptreactjs

提问by Luiz E.

I have a component like this

我有一个这样的组件

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

turns out that the createdAtis a string like 1451589259845and I want to format the date. How can I do that on ReactJS? I tried put new Date()inside the brackets but got an error.

原来这createdAt是一个字符串1451589259845,我想格式化日期。我怎么能在 ReactJS 上做到这一点?我尝试将其new Date()放入括号内,但出现错误。

回答by Mike 'Pomax' Kamermans

Just do it in JS the usual way, before you start your return, and just template that in:

在开始返回之前,只需按照通常的方式在 JS 中执行此操作,然后将其模板化为:

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

And there are quite a few ways you can do the string formatting, Date has a number of them built in (like toLocaleStringor toUTCString), or you can use a dedicated formatter like moment.js

并且有很多方法可以进行字符串格式化,Date 内置了许多方法(例如toLocaleStringtoUTCString),或者您可以使用像moment.js这样的专用格式化程序

回答by Tim Gass

You could just run the regular JavaScript New Date(). However, I would strongly recommend using momentjs, as it seems to be more in line with what you are trying to do.

您可以只运行常规的 JavaScript New Date()。但是,我强烈建议使用 momentjs,因为它似乎更符合您的意图。

On the command line do:

在命令行上执行:

npm install moment --save

npm install moment --save

Then in your code either var moment = require("moment");or import moment from "moment";depending on whether you are using ES6 or not.

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

After that, I would run code like so.

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

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

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

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

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

Also, it may seem like a huge pain to install a package to do this, but moment is really nice and I would highly recommend it. The reason I recommended it is that it humanizestimes. Like for instance, the fromNow() formatting makes it say 30 seconds ago, 4 days ago, or 3 months ago. It makes it sound like a person wrote it and it doesn't display tons of unnecessary info unless specified. I mean, most people don't want to know how many minutes and seconds ago it was if it was several hours ago. So, I recommended this library for those reasons. Feel free to use vanilla JS though if you prefer, I just find that moment is very nice for presentational purposes and let's me avoid having to write tons of math functions to display months, etc.

此外,安装一个软件包来执行此操作似乎很痛苦,但 moment 真的很好,我强烈推荐它。我推荐它的原因是它使时代人性化。例如, fromNow() 格式使它表示 30 秒前、4 天前或 3 个月前。这听起来像是一个人写的,除非指定,否则它不会显示大量不必要的信息。我的意思是,如果是几个小时前,大多数人不想知道是多少分钟和几秒前。因此,出于这些原因,我推荐了这个库。如果您愿意,可以随意使用 vanilla JS,我只是发现那一刻非常适合展示目的,让我避免编写大量数学函数来显示月份等。

回答by Michael

Want this format?

想要这种格式?

Wed, May 30, 2018`

2018 年 5 月 30 日,星期三`

Just declare

只需声明

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

And then in your React JS code

然后在你的 React JS 代码中

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

toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date

Source and more options

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

来源和更多选项

回答by Jitendra

You can use Intl.DateTimeFormat to control over the time formatting. The Intl.DateTimeFormatobject is a constructor for objects that enable the language-sensitive date and time formatting.

您可以使用 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>

It will result in an example: "17 December 2019" format.

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

回答by stacksonstacksonstacks

In React WITHOUT moment.js

在没有 moment.js 的 React 中

    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

回答by cachess

Just a follow up all your answers are correct but I follow this code. Can I format my dates before it will pass down to my array using Moment. But the start only gives me an undefined value

只需跟进您的所有答案都是正确的,但我遵循此代码。我可以在日期使用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,
}));