簡體   English   中英

計算谷歌雲 function 上的時間戳之間的差異

[英]Calculate the difference between timestamp on google cloud function

我有一個 function 將每天運行以檢查每個帖子的年齡,所以我如何獲得存儲在 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();

但是,差異(毫秒)仍然存在不准確性,因為互聯網延遲......

但是......管理員object......它似乎是服務器代碼,我們通常使用local time - createAt 因為我們的服務器始終連接到互聯網,並且很少延遲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM