Firebase提供了我所知道的以下两种方法,用于在将文档写入Firestore集合时使用日期:
以下内容将生成当前时间戳,我假设它代表所有区域中的一致日期,格式为documentation中注明的格式,这是在将文档写入集合时获取当前日期的推荐方式:
admin.firestore.FieldValue.serverTimestamp()
还有以下方法将日期作为参数。这将生成与Firestore时间戳格式相同的结果:
admin.firestore.Timestamp.fromDate(new Date())
我一直在考虑在我的特殊情况下使用后者作为生成日期的方法,我可以使用该日期将匹配日期写入Firestore中集合中的文档,也可以将其写入实时数据库中。我需要保证将完全相同的日期写到两个地方。
我在云功能中正在做什么:
const datePosted = new Date();
// then when setting the data in Firestore i do the following to convert it
admin.firestore().collection(`/posts`).doc().set({
foo: 'bar',
datePosted: admin.firestore.Timestamp.fromDate(datePosted)
})
// followed by a subsequent write to my Realtime database using the same date
admin.database().ref(`posts`).set({
foo: 'bar',
datePosted: Date.parse(datePosted)
})
任何人都可以提供关于此方法是否是一个坏主意的见解吗?我需要找出以我所描述的方式生成日期是否是有效的方法,或者从文档中生成的日期可能会随云实例的时间和/或区域不同而变化的意义上说,这种方法是否可靠?函数实例化。
admin.firestore.FieldValue.serverTimestamp()
生成一个时间戳,该时间戳被保证是准确的,正如Google认为的那样。即使请求由于某种原因(例如脱机)而延迟,当请求到达Firestore时,实际时间仍将得到解决。