2

In my chess app I use Firebase.ServerValue.TIMESTAMP to record the time of a move.

Suppose that user has 24 hours to make a move. If they do not make a move within 24 hours, they lose the game.

I would like to display how much time user has left to make a move. To calculate this, I need to know the current unix timestamp, and then I would do:

time left = (last move unix timestamp) + (24 hours) - (current unix timestamp)

I feel like assuming that user's machine time is correct might not be the best idea.

Is there a way to get the unix timestamp from Firebase servers?

Related question

Community
  • 1
  • 1
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

1 Answers1

5

You can utilize .info/serverTimeOffset to calculate the difference from local to server:

var getCurrentTimestamp = (function() {
  var OFFSET = 0;

  fbutil.ref("/.info/serverTimeOffset").on('value', function(ss) {
    OFFSET = ss.val()||0;
  });

  return function() {
     return Date.now() + OFFSET;
  }
})();

var now = getCurrentTimestamp();
var delta = now - timestamp;
Kato
  • 40,352
  • 6
  • 119
  • 149
  • Thanks @Kato! The only potential problem is if I call `getCurrentTimestamp()` immediately after it's been defined (like in your example), then `OFFSET` might not be set yet. – Misha Moroshko Aug 26 '14 at 10:09
  • 2
    I'm fairly sure a brilliant mind like yourself can work around that :) In reality, it will be set by the time Firebase has initialized a connection, so if you have some data to compare it to, you'll have an offset. – Kato Aug 26 '14 at 14:28
  • i'm using const fbutil = require('@firebase/util'); but get error: TypeError: fbutil.ref is not a function. (In 'fbutil.ref('/.info/serverTimeOffset')', 'fbutil.ref' is undefined) – 691138 Dec 16 '19 at 04:34