How can you get the server time from Firebase

NSCoder picture NSCoder · Jun 13, 2014 · Viewed 29.9k times · Source

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?

Answer

canbax picture canbax · Sep 25, 2017

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