Firebase Timestamp in cloud function not displaying time

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 08:14:25

问题


I am using this to get the timestamp

admin.database.ServerValue.TIMESTAMP

But in log getting this while doing console the variable

{ '.sv': 'timestamp' }

anyone help me out in this.

Actually i want to get the timestamp then compare it with db timestamp


回答1:


The admin.database.ServerValue.TIMESTAMP does not contain the actual server-side timestamp, but is merely a marker (the { '.sv': 'timestamp' } that you see). The database server recognizes this marker on write operations, and then writes the server-side timestamp in its place.

This means that you can't get the server-side timestamp without writing to the database. A simple way to see how to get this is:

let ref = firebase.database().ref("test");
ref.on("value", function(snapshot) {
  console.log(snapshot.val());
})
ref.set(admin.database.ServerValue.TIMESTAMP)

When you run this code, your log will show three values:

  1. null

    This is the current value in the database when you attach the listener with on("value". Here I'm assuming the test node didn't exist yet, so the value would be null.

  2. 1573659849577

    This is an estimate that the client makes when you the ref.set(...) statement executes. So the client estimates what it thinks the server timestamp may be, and fires a value event. You can use this to update the UI immediately, so that the user doesn't have to wait.

  3. 1573659859162

    This is the value that the server actually wrote to the database, and then sent back to the client. So this is the actual server-side timestamp that you're looking for.

In theory the client-side estimate (2) and server-side value (3) may be the same, in which case you wouldn't get the third event. But I've never seen that in practice, as they're always off by at least a couple of milliseconds.



来源:https://stackoverflow.com/questions/58835383/firebase-timestamp-in-cloud-function-not-displaying-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!