javascript - 在 React Native 中连接日期和时间返回 'Invalid Date'

标签 javascript datetime react-native momentjs

我的 React-Native 应用程序中有两个字段,一个用于日期,一个用于时间。日期字段返回格式为“YYYY-MM-DD”的值,时间字段返回格式为“hh:mm A”的值。我使用 moment 进行格式转换。最终的 API 调用应使用格式为“YYYY-MM-DDTHH:mm”的单个条目进行,因此要连接我使用的日期和时间,

moment(date+ " "+time).format("YYYY-MM-DDTHH:mm:ss")

它在我的 Android 和 iOS 模拟器中运行良好,当我在设备上调试时也运行良好,但一旦我为两者进行构建,它就会开始返回

Invalid Date.

编辑:尝试过moment(date + ""+ value).format();,也在构建中返回“无效日期”。 还尝试直接使用 Date new Date(date+ ""+ time); 执行此操作,而不提供任何格式,也会在构建中返回“无效日期”。

最佳答案

您必须使用moment(String, String)因为您的输入既不是 ISO 8601 格式也不是 RFC 2822 格式。

moment(String)状态:

When creating a moment from a string, we first check if the string matches known ISO 8601formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

根据您的情况,您可以使用:

moment(date+ " "+time, "YYYY-MM-DD hh:mm a").format("YYYY-MM-DDTHH:mm:ss")

关于javascript - 在 React Native 中连接日期和时间返回 'Invalid Date',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45227312/

相关文章:

javascript - 如何在 Canvas 上绘制经过三个点的曲线?

wpf - DateTime 属性在更改时不会触发 PropertyChanged 事件

react-native - android的React Native fetch()网络请求失败?

javascript - 引用错误: require is not defined [javascript]

javascript - 设计 MongoDB 数据库 - 许多嵌入式文档可以吗?

r - R中日期之间的差异

react-native - 如果构建是强制性的,如何只显示更新对话框

javascript - react-native 中的后台服务

javascript - jQuery 创建新数组并将旧数组加倍

php - MySQL now() 和更新时间之间的时间差