Home > front end >  Firebase Timestamp Syncing
Firebase Timestamp Syncing

Time:04-07

In my turn based online game I have a timer in-game, that ticks down from 24 hours to 0, when it reaches 0 for any player they have lost. When a player makes their turn they write something like this to the database:

action: "not important"
timeStamp: 1670000000

What I want is for either of the two players to be able to get into the ongoing game at any time, read "timeStamp" and set the clock accordingly, showing how much time is left since the last action.

When writing to the database I am using ServerValue.TIMESTAMP (Android). I am aware of the ability to estimate the server time using ServerTimeOffset described here;

https://firebase.google.com/docs/database/android/offline-capabilities#server-timestamps

But I feel it's not always accurate when testing, so I wanted to explore if there is any other way to do this. What I really want is to get the actual server timestamp when reading the node:

timeLeft = actionTimeStamp - currentServerTime 24h

Is this possible to do in ONE call? I am using RTDB, but I am open to moving to Firestore if it is possible there somehow.

CodePudding user response:

There's no way to get the server timestamp without writing it to the database, but you can of course have each client write it and then immediately read it back.

That said, it shouldn't make much of a difference from using the initial start time that was written and the serverTimeOffset value.

For a working example, have a look at How to implement a distributed countdown timer in Firebase

  • Related