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?
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?
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;
});
For firebase3, please use firebase.database.ServerValue.TIMESTAMP
$scope.createdDate = firebase.database.ServerValue.TIMESTAMP
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);
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.
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 firebase.firestore.Timestamp.now()
returns the client time. –
Copal © 2022 - 2024 — McMap. All rights reserved.