Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当前时间戳和数据库时间戳之间的Firebase时间戳差异错误_Firebase_Google Cloud Firestore - Fatal编程技术网

当前时间戳和数据库时间戳之间的Firebase时间戳差异错误

当前时间戳和数据库时间戳之间的Firebase时间戳差异错误,firebase,google-cloud-firestore,Firebase,Google Cloud Firestore,我编写了一个TimeValidityCheckUtil,它确定来自特定侦听器的快照是否在设备当前时间的给定时间范围内。这有一个方法,checkIfTImeValid public static boolean checkIfTimeValid(Timestamp dbTimestamp) { Timestamp currentTimestamp = Timestamp.now(); Long seconds = currentTimes

我编写了一个
TimeValidityCheckUtil
,它确定来自特定侦听器的快照是否在设备当前时间的给定时间范围内。这有一个方法,
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中,如下所示:

"ABC"-|
      |
      |-"documentId"-|
                     |
                     |-"some_key" - "string"
                     |-"timestamp" - timestamp
这就是发生的情况,设备A创建一个documentId和带有时间戳的对象

设备B侦听此documentId并调用
checkIfTimeValid
检查文档A的操作是否在当前时间戳的10秒内(检查是否是最近的)

即使该过程立即发生,设备也会将时间戳之间的差异显示为~57-62s,根据我的说法,时间戳之间的差异不应超过1-5s

为什么会发生这种情况?

时间戳。现在()
使用本地设备的时间计算。如果设备时钟与Firebase不同步,此差异将在此处反映出来

我不知道Firestore的等效值,但在RTDB中,您可以使用特殊位置
/.info/serverTimeOffset
来估计时钟之间的毫秒差

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)

您从何处调用此方法?请添加更多上下文。请将您的数据库结构添加为屏幕截图。嘿@AlexMamo,我已经做了建议的更改。您也可以“ping”time.google.com,GCP/函数使用它来手动估计客户端设备的时间偏移。谢谢@samthecodingman。有没有一种方法我总是从服务器而不是本地设备的时间获取时间戳,这样我就不必依赖于偏移量估计?这就是SNTP客户端的用途。它将返回服务器时间戳,因为Firestore没有等效项。