简体   繁体   English

如何在 React 中格式化日期

[英]How to format a date in React

How do I format a date in React?如何在 React 中格式化日期?

The date comes in the form <pubDate>Thu, 22 Mar 2018 14:11:40 GMT</pubDate> .日期的格式为<pubDate>Thu, 22 Mar 2018 14:11:40 GMT</pubDate>

I would like to display only 22 Mar 2018 .我只想显示22 Mar 2018

  render() {
    return (
      <div>
        {this.state.posts.map(function(item, i) {
          return (
            <li key={item.guid}>
              <time className="MediumPost-time">{item.pubDate}</time>
            </li>
          )
        })}
      </div>
    )
  }

Edited After installing Moment.js with npm install moment --save , I used it successfully this way:编辑使用npm install moment --save安装 Moment.js 后,我以这种方式成功使用了它:

import React, { Component } from 'react';
import moment from 'moment'

class PrettyDate extends Component {

  render() {
    return (
      <time className="MediumPost-time">{moment(item.pubDate).format('ll')}</time>
    )
  }
}

export default PrettyDate;

不依赖lib的JavaScript解决方案是item.pubDate.split(" ").slice(1, 4).join(" ")但是如果您已经安装了它,则可以考虑使用moment

you can format the date like that.你可以这样格式化日期。

function myDate() {
  const date = new Date(2018,3,22);
  const year = date.getFullYear();
  const month = date.toLocaleString("en-US", { month: "long" });
  const day = date.toLocaleString("en-US", { day: "2-digit" });
  

  return (
    <div>
      <span>{day}</span>
      <span>{month}</span>
      <span>{year}</span>
    </div>
  );
}

export default myDate;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM