计算谷歌云函数上时间戳之间的差异



我有一个函数,每天运行它来检查每个帖子的年龄,这样我就可以获得我存储在Firestore中的时间戳(以时间戳类型存储(和当前时间戳之间的差异(以秒为单位(。

exports.dailyCheckPost = functions.runWith(runtimeOptions).pubsub.schedule("28 15 * * *").timeZone('Asia/Kuala_Lumpur').onRun(async () => {
console.log("Function Running!")
const snapshot = await firestore.collection("post").where("isPublished","==",true).get();
snapshot.forEach(async (doc) => {
const data = doc.data()
var difference = admin.firestore.Timestamp.now() - data.createdAt
firestore.collection("users").doc(doc.id).set({
age : difference
},
{
merge: true
})
})
});

所以。。。

var difference = new Date().valueOf() - data.createdAt.toDate().valueOf();

如果你想知道谷歌的实时。。。

admin.firestore().collection("time").doc("timeDoc").update({
updateAt:firebase.firestore.FieldValue.serverTimestamp()
}
const query = admin.firestore().collection("time").doc("timeDoc").get();
var difference = query.data().createAt.toDate().valueOf() - data.createdAt.toDate().valueOf();

然而,由于网络延迟,差异(ms(仍然存在不精确性。。。

但是。。。管理对象。。。似乎是服务器代码,我们通常使用local time - createAt。因为我们的服务器总是连接到互联网,很少延迟。

最新更新