如何从Firebase获取服务器时间 [英] How can you get the server time from Firebase

查看:143
本文介绍了如何从Firebase获取服务器时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将angularjs与firebase一起使用,并且在使用时

I'm using angularjs with firebase and when I use

$scope.createdDate = new Date();

它使用客户端上的时间,但是我想使用Firebase Servers的当前时间,因为客户端时间可能会有所不同.我怎样才能做到这一点呢?

it uses the time on the client, however I want to use Firebase Servers current time as client-side time may vary. How can I go about this in angular?

推荐答案

打印firebase.database.ServerValue.TIMESTAMP时,它将为您提供该对象{.sv: "timestamp"}

When you print firebase.database.ServerValue.TIMESTAMP it will give you this object {.sv: "timestamp"}

要获取客户端上的Firebase服务器的时间戳,您首先需要值写入服务器,然后读取.

To reach the timestamp of firebase server on client, you first need to write the value to the server then read the value.

 firebase.database().ref('currentTime/').update({ time: firebase.database.ServerValue.TIMESTAMP })
    .then(function (data) {
      firebase.database().ref('currentTime/')
        .once('value')
        .then(function (data) {

          var t = data.val()['time'];
          console.log('server time: ', t);

        }, function serverTimeErr(err) {
          console.log('coulnd nt reach to the server time !');
        });
    }, function (err) {
      console.log ('set time error:', err)
    });

我认为必须有一种更简便的方法来直接从客户端读取服务器时间戳.

I think there must be an easier way to directly read the server timestamp from client.

刚刚发现了一种更好的方法,可以使用1个调用来触发火力发源

edit 1: just found a better way uses 1 call to firebase

firebase.database().ref('/.info/serverTimeOffset')
  .once('value')
  .then(function stv(data) {
    console.log(data.val() + Date.now());
  }, function (err) {
    return err;
  });

这篇关于如何从Firebase获取服务器时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆