Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you get the server time from Firebase

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?

like image 739
NSCoder Avatar asked Jun 13 '14 09:06

NSCoder


People also ask

What is Firebase timestamp?

A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.

What is Firebase real time?

The Firebase Realtime Database is a cloud-hosted NoSQL database that lets you store and sync data between your users in realtime. NEW: Cloud Firestore enables you to store, sync and query app data at global scale.

Is Firebase firestore real time?

Firebase offers two cloud-based, client-accessible database solutions that support realtime data syncing: Cloud Firestore is Firebase's newest database for mobile app development. It builds on the successes of the Realtime Database with a new, more intuitive data model.


1 Answers

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;
  });
like image 64
canbax Avatar answered Sep 20 '22 11:09

canbax