How can you get the server time from Firebase
Asked Answered
T

4

15

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?

Titanothere answered 13/6, 2014 at 9:58 Comment(1)
is it this? firebase.com/docs/managing-presence.html#server-timestampsNim
P
19

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;
  });
Planarian answered 25/9, 2017 at 8:55 Comment(8)
hey, i used your methode but i keep getting a wrong datePhoebephoebus
how do u know if it is wrong? It is the time in the firebase server.Planarian
i got this timestamp = 1535916727292 which is equal to 07 April 50641. Is this normal?Phoebephoebus
my code after edit 1 looks pretty simple and it was working. Maybe firebase api changedPlanarian
@FirasChebbah It's ms since epoch, not seconds. Divide by 1000 if you want seconds.Wamble
I highly doubt the code in edit1 works. Just to be clear if both the time on client and the server are accurate, the conversion works. But half the time the point of checking the server time is that we don't trust the device's clock. In those cases the solution doesn't help.Golgi
@Golgi If you need to have atomic precision of course it doesn't help. In the end, we are bounded by the hardware we use. firebase uses websocket for communication. So it should be faster than HTTP. I think this solution is the best possible solution.Planarian
@Planarian I'm not talking about atomic precision. For games some ppl change their device's clock to get around the time limits the games impose. Like if there is a daily ad they can watch only once a day, they set their clock to 24 hours ahead to see multiple ads per day. For those cases, you need the server time coming from the server without checking the device's clock. The first solution in this answer works for this use case.Golgi
D
15

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

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

doc here

Delinquent answered 12/7, 2016 at 19:46 Comment(4)
Is there a way to get the server time without having to set it first ? (It's quite of weird to set it, then get it with a once, then try to take into account the delay is has taken to set it and then get it, and finally erase it).Roentgenology
I didn't get it well, dear. You can use firebase.database.ServerValue.TIMESTAMP anytime without using .set method or others.Delinquent
When trying to access the content of firebase.database.ServerValue.TIMESTAMP from client-side, it throws the object {.sv: "timestamp"} . I believe it's a reference that is replaced automatically on the server side when seting or updating.Methinks
Verified in this Docs Reference: ServerValue.TIMESTAMP is A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) by the Firebase Database servers.Methinks
T
7

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);
Titanothere answered 13/6, 2014 at 11:4 Comment(0)
I
-1

2020: Now you can use firebase.firestore.Timestamp.now() to get the UNIX time from the server. It returns an object that looks like this:

{
    seconds: NUM_OF_SECONDS,
    nanoseconds: NUM_OF_NANOSECONDS
}

From this in the docs.

Incise answered 31/5, 2020 at 20:19 Comment(5)
I'm pretty sure that the now() function on a client does not perform a server request. Instead it will return the current client date. The documentation states "Creates a new timestamp with the current date, with millisecond precision".Glanders
I just tested it by changing my computer clock. firebase.firestore.Timestamp.now() returns the client time.Copal
yes ... so seems like there is no way doing it without cloud function ? :( @JohnnyOshikaBedeck
@DaniilKunin Yeah, you'll need to call a server somewhere to get a trustable server timeCopal
makes sense! 👍 @JohnnyOshikaBedeck

© 2022 - 2024 — McMap. All rights reserved.