Firebase TIMESTAMP to date and Time

后端 未结 18 2557
温柔的废话
温柔的废话 2020-11-27 03:39

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

18条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 04:09

    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 );
    });
    

    Why use this way?

    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

提交回复
热议问题