React Intl v2无法使用<格式化日期>带有来自SQL的日期

React Intl v2 unable to use <FormattedDate> with date from SQL

本文关键字:日期 gt SQL Intl 格式化 v2 React lt      更新时间:2023-09-26

我一直在用React构建一个演示,并遇到了React-intl。我尝试使用带有"value"的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" />
    )
}

在代码中,我们看到组件使用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

知道为什么会发生这种事吗?我也尝试过将裸字符串分配为"value",以及(new Date(date.parse(this.state.booking.checkIn),但所有这些都会产生范围错误。

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

要获取您提供的代码片段,而不是:

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

它返回类似于:

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

formatjs不接受分为60秒以上的分钟(正如预期的那样)。

出于我的需要,我不在乎秒数,所以在将秒数传递给formatjs之前,我只从字符串中删除了秒数,就解决了这个问题。