Reputation: 171
I am trying to use Firebase's timestamp, but I don't understand the documentation for JavaScript. How do you convert the value retrieved to time (i.e 4:00pm)This is the page I have been using: https://firebase.google.com/docs/database/web/offline-capabilities#server-timestamps
It seems that you use .set(firebase.database.ServerValue.TIMESTAMP);
to set the timestamp and
var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
var offset = snap.val();
var estimatedServerTimeMs = new Date().getTime() + offset;
});
to get retrieve the timestamp and client's clock skew. Since you are retrieving a "A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers," it seems that you cannot do it the way the person asked here which is how I would have done it: Firebase TIMESTAMP to date and Time
var timestamp = '1452488445471';
var myDate = new Date(timestamp);
I don't really understand the answer:
fb.ref("/.info/serverTimeOffset").on('value', function(offset) {
var offsetVal = offset.val() || 0;
var serverTime = Date.now() + offsetVal;
});
This is what I have:
let timestamp;
let timestampRef = firebase.database().ref("server");
timestampRef.set(firebase.database.ServerValue.TIMESTAMP);
timestampRef.on("value", function(snap) {
let offset = snap.val();
let estimatedServerTimeMs = new Date().getTime() + offset;
console.log("time stamp: ", timestampRef);
console.log("offset: ", offset);
console.log("estimatedServerTimeMs: ", estimatedServerTimeMs);
});
Upvotes: 2
Views: 3699
Reputation: 317392
You've overcomplicating things. You don't need any offsets to read the time that was written by the server timestamp token. The date value expressed as number of milliseconds since unix epoch will just appear as an integer that you can feed to new Date()
after it's been interpreted by the server.
Upvotes: 1