在反应式网络应用中,我有一个<input type="datetime-local">
的表单。
Windows上的chrome版本64中返回的值采用以下格式:
2018-03-08T07:00
我认为在其他浏览器中它会有所不同。
我想在firestore中编写此值,其格式与我在创建时使用firestore管理GUI生成的格式相同,格式为'timestamp'的字段,如下所示:
March 8, 2018 at 7:00:00 AM UTC+2
知道怎么做才能在所有浏览器上运行吗?
答案 0 :(得分:2)
Cloud Firestore以ISO8601格式存储时间戳。如果您使用控制台添加时间戳,然后get
文档,则会返回以下内容。
{"timestamp":"2018-03-16T15:45:36.000Z"}
我建议您将所有时间转换为通用格式,这样您的数据库中就没有不同的时间格式。一个很好的工具,是moment.js。我建议使用ISO8601格式,因为大多数(如果不是全部)浏览器,应用程序,数据库等都可以使用这种格式。
答案 1 :(得分:1)
我在状态中设置了默认/初始值:
this.state={
datetime: `${new Date().getFullYear()}-${`${new Date().getMonth()+1}`.padStart(2,0)}-${`${new Date().getDay() + 1}`.padStart(2,0)}T${`${new Date().getHours()}`.padStart(2,0)}:${`${new Date().getMinutes()}`.padStart(2, 0)}`
}
然后我创建一个使用上面的状态值的受控输入...
<input
type="datetime-local"
name="datetime"
value={this.state.datetime}
onChange={e => this.setState({datetime: e.target.value})}
/>
有点冗长,但它对我有用。
答案 2 :(得分:0)
要格式化日期,您应该使用以下格式:
this.state={
datetime: `${new Date().getFullYear()}-${`${new Date().getMonth()+1}`.padStart(2,0)}-${`${new Date().getDate()}`.padStart(2,0)}T${`${new Date().getHours()}`.padStart(2,0)}:${`${new Date().getMinutes()}`.padStart(2, 0)}`
}
注意:从Josh的答案中,我将getDay()更改为getDate(),因为第一个返回星期几(0 -6),所以我没有足够的声誉对其进行评论