javascript - React Intl v2 无法将 <FormattedDate> 与来自 SQL 的日期一起使用

标签 javascript reactjs formatjs

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

但是页面无法加载并且控制台显示: RangeError: Provided date is not in valid range,代码如下。

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),但都产生范围错误.

最佳答案

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

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

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

它返回如下内容:

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

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

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

关于javascript - React Intl v2 无法将 <FormattedDate> 与来自 SQL 的日期一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33485516/

相关文章:

javascript - NodeJs - Controller 内的异步/等待

javascript - OpenLayer map 标记不起作用

javascript - 在条形图顶部显示计数 - ChartJS

javascript - Google 行车路线至最近的道路

reactjs - 即使在 React 中选中,复选框也总是传递 false

javascript - 如何从 async/await 函数正确返回结果?

javascript - `event` 对象在 this.setState() 中无法访问 - React.js

reactjs - 在@formatjs/intl-relativetimeformat/dist/locale-data/中哪里可以找到美国的语言环境

javascript - 如何输出长日期时间格式,其中包括带有时刻时区和react-intl的时区?