How can you get the server time from Firebase

≯℡__Kan透↙ 提交于 2019-12-10 13:34:22

问题


I'm using angularjs with firebase and when I use

$scope.createdDate = new Date();

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?


回答1:


For firebase3, please use firebase.database.ServerValue.TIMESTAMP

$scope.createdDate = firebase.database.ServerValue.TIMESTAMP

doc here




回答2:


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

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.

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;
  });



回答3:


Thanks to Jonas Grumann for pointing out this firebase doc on how to add server time from firebase.

// Get created date from Firebase servers
var createdDate = new Firebase('https://somedomain.firebaseIO.com/post/createDate');
createdDate.set(Firebase.ServerValue.TIMESTAMP);


来源:https://stackoverflow.com/questions/24202641/how-can-you-get-the-server-time-from-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!