1

我需要向 admin.database.ServerValue.TIMESTAMP 添加时间,然后再检索它。但是当我尝试增加额外的时间时ServerValue.TIMESTAMP我得到一个错误:

getTime 不是函数

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const ten_secs = 10 * 1000; // 10 seconds
const daily_secs = 24 * 60 * 60 * 1000; // 24 hrs
const weekly_secs = 168 * 60 * 60 * 1000; // 1 week

exports.update = functions.https.onRequest((request, response) => {

    const currentTimeStamp = admin.database.ServerValue.TIMESTAMP;

    const updatedSecs = new Date(currentTimeStamp.getTime() + ten_secs); // should be saved in the db as milliseconds for later retrieve and calculations

    const updatedDay = new Date(currentTimeStamp.getTime() + daily_secs); // should be saved in the db as milliseconds for later retrieve and calculations

    const updatedWeek = new Date(currentTimeStamp.getTime() + weekly_secs); // should be saved in the db as milliseconds for later retrieve and calculations

    console.log("updatedSecs: " + updatedSecs + " | updatedDay: " + updatedDay + " | updatedWeek: " + updatedWeek);

    const ref = admin.database().ref('schedule').child("scheduleId_123").child("my_uid")

    ref.once('value', snapshot => {

        if (!snapshot.exists()) {

            return ref.set({ "updatedSecs": updatedSecs, "updatedDay": updatedDay, "updatedWeek": updatedWeek });

        } else {

            const retrieved_updatedSecs = snapshot.child("updatedSecs").val();
            const retrieved_updatedDay = snapshot.child("updatedDay").val();
            const retrieved_updatedWeek = snapshot.child("updatedWeek").val();

            const currentTime = Date.now();

            // do some calculations with the above values and currentTime.
        }
    });
}
4

3 回答 3

1

ServerValue.TIMESTAMP不是您可以进行数学运算的标准整数时间戳记值。它是一个令牌或哨兵值,当服务器接收到写入时会在服务器上进行解释。这就是它能够获取实际服务器的时间戳值的方式。唯一有意义的使用方法是在写作时作为孩子的价值。

由于您在 Cloud Functions 中运行,因此您实际上在内存中有一个 Google 服务器时间戳值 - 在实际时钟中。Google 的所有后端都有同步时钟,因此它们都是准确的。ServerValue.TIMESTAMP当您不能确定用户的设备有准确的时钟时,您通常只在客户端应用程序中使用。

在您的情况下ServerValue.TIMESTAMP,您应该简单地将Date.now()其作为当前时间,而不是使用。

于 2020-11-10T03:57:25.043 回答
0

currentTimeStamp 之后需要一个右括号。

const updatedSecs = new Date(currentTimeStamp).getTime() + ten_secs;
于 2020-11-10T03:42:50.610 回答
0

@DougStevenson 的回答有效,但我遇到了另一个getTime is not a function仍然出现的问题。我不得不.valueOf()改用。

这是更新的代码:

const currentTimeStamp = Date.now(); // DougStevenson answer

const updatedSecs = currentTimeStamp.valueOf() + ten_secs;

const updatedDay = currentTimeStamp.valueOf() + daily_secs;

const updatedWeek = currentTimeStamp.valueOf() + weekly_secs;
于 2020-11-10T04:30:20.233 回答