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?
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.
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.
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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With