【问题标题】:React Intl v2 unable to use <FormattedDate> with date from SQLReact Intl v2 无法将 <FormattedDate> 与 SQL 中的日期一起使用
【发布时间】:2015-11-02 19:39:54
【问题描述】:

我一直在使用 React 构建一个演示,并遇到了 react-intl。我尝试将 FormattedDate 组件与从 API 调用返回并存储在“this.state”中的“值”一起使用

但是页面加载失败,控制台显示: RangeError: 提供的日期不在有效范围内,代码如下。

index.js

ReactDOM.render(
    <IntlProvider locale='en'>
      <Router>
        <Route path="/" component={App}>
          <IndexRoute component={Login} />
          <Route path="bookings" component={Bookings} />
          <Route path="bookings/:id" component={BookingDetail} />
          <Route path="create" component={BookingCreate} />
        </Route>
      </Router>
    </IntlProvider>,
    document.getElementById('react-container')
);

在我的组件的渲染中我有,

render() {
    return (
      <FormattedDate value={new Date(this.state.booking.checkIn)}  day="numeric" month="long" year="numeric" />
    )
}

code 中,我们看到该组件使用Intl.DateTimeFormat.prototype.format 来生成格式化日期,但是当我在 Node repl

中执行相同操作时
var date = '2015-10-30T23:53:28.879Z'
console.log(new Intl.DateTimeFormat().format(new Date(date)));

10/30/2015 //It produces the correct output

知道为什么会这样吗?我也试过将裸字符串分配为“值”,以及(new Date(date.parse(this.state.booking.checkIn),但都产生范围错误。

【问题讨论】:

    标签: javascript reactjs formatjs


    【解决方案1】:

    我也遇到过类似的问题。查看我的日志,我注意到一些库(在我的例子中是 momentjs)返回一个完整的日期,分钟分为 100 秒。

    获取您提供的代码 sn-p,而不是:

     '2015-10-30T23:53:28.879Z'
    

    它返回类似:

     '2015-10-30T23:53:86.879Z'
    

    formatjs 不接受将分钟划分为超过 60 秒(如预期的那样)。

    出于我的需要,我不关心秒数,所以我通过在将字符串传递给 formatjs 之前从字符串中删除秒数来解决这个问题。

    【讨论】:

    • 在我的情况下,我想要几秒钟,所以我在发送到 react-intl 之前做了new Date(dateString)
    猜你喜欢
    • 2017-05-05
    • 2017-10-12
    • 2016-08-11
    • 2021-04-25
    • 2017-10-05
    • 1970-01-01
    • 2018-11-15
    • 2015-09-06
    • 1970-01-01
    相关资源
    最近更新 更多