【问题标题】:How to change the display format of date in react-intl?如何更改 react-intl 中日期的显示格式?
【发布时间】:2016-08-22 12:54:39
【问题描述】:

我需要使用 react-intl 使用不同的分隔符来显示日期。 到目前为止我有这个

const date = new Date("2016-08-12T16:59:02.013+02:00");
...
return() {
   render(
      <FormattedDate
            value={date}
            year='numeric'
            month='numeric'
            day='numeric'
          />
   )
}

这会呈现日期 8/12/2016,但我需要像这样显示它8-12-2016。 FormattedDate 如何做到这一点?还是我应该使用不同的方法?

【问题讨论】:

  • 使用 localeMatcher="lookup" 和 locale="en-in"。

标签: javascript date reactjs react-intl


【解决方案1】:

首先,从 react-intl 包中导入hoc

import {injectIntl} from 'react-intl'

然后将其应用到您的组件:

injectIntl(YourReactComponent)

它将使您可以通过YourReactComponent 中的props 访问formatDate 方法。该方法由FormattedDate 的实例在内部使用,它返回格式化日期的字符串表示形式:

  const stringDate = this.props.intl.formatDate(date, // your date variable
            {
                year:'numeric',
                month:'numeric',
                day:'numeric'
            })

stringDate现在包含8/12/2016,你可以随意修改:

const stringWithHyphens = stringDate.replace(/\//g, "-"); // replacing all '/'s with '-'s

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    相关资源
    最近更新 更多