I am using firebase for my chat application. In chat object I am adding time stamp using Firebase.ServerValue.TIMESTAMP
method.
I need to show the messa
inside Firebase Functions transform the timestamp like so:
timestampObj.toDate()
timestampObj.toMillis().toString()
documentation here https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp
Firebase.ServerValue.TIMESTAMP is not actual timestamp it is constant that will be replaced with actual value in server if you have it set into some variable.
mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP });
mySessionRef.on('value', function(snapshot){ console.log(snapshot.val()) })
//{startedAt: 1452508763895}
if you want to get server time then you can use following code
fb.ref("/.info/serverTimeOffset").on('value', function(offset) {
var offsetVal = offset.val() || 0;
var serverTime = Date.now() + offsetVal;
});
It is simple. Use that function to get server timestamp as milliseconds one time only:
var getServerTime = function( cb ) {
this.db.ref( '.info/serverTimeOffset' ).once( 'value', function( snap ) {
var offset = snap.val();
// Get server time by milliseconds
cb( new Date().getTime() + offset );
});
};
Now you can use it anywhere like that:
getServerTime( function( now ) {
console.log( now );
});
According to latest Firebase documentation, you should convert your Firebase timestamp into milliseconds. So you can use estimatedServerTimeMs
variable below:
var offsetRef = firebase.database().ref(".info/serverTimeOffset");
offsetRef.on("value", function(snap) {
var offset = snap.val();
var estimatedServerTimeMs = new Date().getTime() + offset;
});
While firebase.database.ServerValue.TIMESTAMP is much more accurate, and preferable for most read/write operations, it can occasionally be useful to estimate the client's clock skew with respect to the Firebase Realtime Database's servers. You can attach a callback to the location /.info/serverTimeOffset to obtain the value, in milliseconds, that Firebase Realtime Database clients add to the local reported time (epoch time in milliseconds) to estimate the server time. Note that this offset's accuracy can be affected by networking latency, and so is useful primarily for discovering large (> 1 second) discrepancies in clock time.
https://firebase.google.com/docs/database/web/offline-capabilities
var date = new Date((1578316263249));//data[k].timestamp
console.log(date);
Try this one,
var timestamp = firebase.firestore.FieldValue.serverTimestamp()
var timestamp2 = new Date(timestamp.toDate()).toUTCString()
Firebase.ServerValue.TIMESTAMP
is the same as new Date().getTime()
.
Convert it:
var timestamp = '1452488445471';
var myDate = new Date(timestamp).getTime();