firebase 时间戳不是服务器端创建的

firebase timestamps not serverside created

我有一个使用 firebase 的本机反应聊天应用程序,对我来说至关重要的是,时间戳全部同步并在服务器端创建,而不是从客户端创建。客户端可以有不同的时间,具体取决于手机上的设置 phone。

我尝试了以下函数来证明我的观点:

const comparetimes = async () => {
        const timezone1  = firebase.firestore.Timestamp.now();
        const timezone2 = (firebase.firestore.Timestamp.now()).toMillis();
        const timezone3 = Date.now();

        console.log(timezone1);
        console.log(timezone2);
        console.log(timezone3)


    }

让我震惊的是这个函数的结果:

{"nanoseconds": 79000000, "seconds": 1641054839}
1641054839080
1641054839080

显然,firebase 时间戳与 Date.now() 完全相同,后者是直接从移动设备 phone 获取的时间戳,因此不准确。

我该怎么做才能让时间戳 不是 由客户端创建,而是由服务器创建,在此示例中为 firebase?我需要检查一些 API 还是我错过了什么?

当您调用 Timestamp.now() 时,它实际上只是在客户端设备上获取时间戳。这是预期的。

阅读 documentation 如何使用服务器时间戳。您必须使用 firestore.FieldValue.serverTimestamp() 返回的令牌值,以便告诉 Firestore 在请求到达服务器时使用当前时刻。

When storing timestamps, it is recommended you use the serverTimestamp static method on the FieldValue class. When written to the database, the Firebase servers will write a new timestamp based on their time, rather than the clients. This helps resolve any data consistency issues with different client timezones:

firestore().doc('users/ABC').update({
  createdAt: firestore.FieldValue.serverTimestamp(),
});

另请阅读: