问题描述
我写了一个 TimeValidityCheckUtil
,它确定来自特定侦听器的快照是否在设备当前时间的给定时间范围内.此方法具有 checkIfTImeValid
I have written a TimeValidityCheckUtil
which determines if the snapshot from a particular listener is within a given time-frame of the current time of the device. This has this method, checkIfTImeValid
public static boolean checkIfTimeValid(Timestamp dbTimestamp)
{
Timestamp currentTimestamp = Timestamp.now();
Long seconds = currentTimestamp.getSeconds() - dbTimestamp.getSeconds();
if(seconds> 10)
{
return false;
}
return true;
}
数据库结构位于Firestore中,如下所示:
The database structure is in Firestore and is as follows:
"ABC"-|
|
|-"documentId"-|
|
|-"some_key" - "string"
|-"timestamp" - timestamp
这就是发生的情况,设备A创建了一个documentId和带有时间戳的对象.
This is what happens, device A creates a documentId and the object with the timestamp.
设备B侦听此documentId并调用 checkIfTimeValid
来检查文档A的操作是否在当前时间戳的10s之内(以检查它是否是最近的)
Device B listens to this documentId and invokes the checkIfTimeValid
to check if the the operation by document A was within 10s of the current Timestamp (to check if it's recent)
即使此过程是立即发生的,设备也会显示时间戳之间的差异为〜57-62s,根据我的说法,该差异不应超过1-5s.
Even if this process is happening instantly, the device shows the difference between the timestamps as ~57-62s which according to me should not be more than 1-5s.
为什么会这样?
推荐答案
Timestamp.now()
是使用本地设备的时间计算的.如果设备时钟与Firebase不同步,则会在此处反映出这种差异.
Timestamp.now()
is calculated using the local device's time. If the device clock is out of sync with Firebase, that difference will be reflected here.
我不知道Firestore的等效功能,但是在RTDB中,您可以使用特殊位置/.info/serverTimeOffset
来估计时钟之间的差异(以毫秒为单位).
I am not aware of the Firestore equivalent, but in the RTDB, you can use special location /.info/serverTimeOffset
to estimate the difference between clocks in milliseconds.
firebase.database().ref('/.info/serverTimeOffset').once('value')
.then((snap) => {
var offset = snap.val();
console.log('Server time delta in ms: ', offset);
// var estimatedServerTimeMs = new Date().getTime() + offset;
})
.catch(console.error)
这篇关于当前时间戳和数据库时间戳错误之间的Firebase时间戳差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!