firebase.database.ServerValue.TIMESTAMP return an Object

10,857

Solution 1

This snippet from the Firebase documentation shows how to set a timestamp:

var userLastOnlineRef = firebase.database().ref("users/joe/lastOnline");
userLastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);

To also have the value available in your code, you need to listen for the value:

userLastOnlineRef.on('value', function(snapshot) {
    console.log(snapshot.val());
});

You'll see the value event fire twice (on the device that sets the value): once for the initial client-side estimate of the timestamp and once for the actual value from the server.

Solution 2

It's expected that you will use firebase.database.ServerValue.TIMESTAMP in data that's written to the Firebase database. It's a placeholder for the actual time on the server and will be replaced when the server receives and writes the data.

You will see the actual timestamp value when you read the data from the database or when any listeners you have might have already configured fire (for child_added, child_changed, or value events etc.).

It's explained in the documentation here:

{TIMESTAMP: non-null Object}

A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers.

Solution 3

This is what I had to do:

firebase.firestore.FieldValue.serverTimestamp()

Source:

https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue

Solution 4

Just to add some more to answer from @cartant:

admin.database.ServerValue.TIMESTAMP returns a non-null Object and is a placeholder value for auto-populating the current timestamp. It doesn't contain the actual timestamp. The database will replace this placeholder when it will execute the command.

It works as you expect when you are using it inside a database.ref but outside of it is just an useless Object.

See this SO Answer for more.

Share:
10,857
mutlucan96
Author by

mutlucan96

Updated on June 04, 2022

Comments

  • mutlucan96
    mutlucan96 about 2 years

    I'm working on a web project with Firebase. I call:

    firebase.database.ServerValue.TIMESTAMP
    

    and it returns:

    {.sv: "timestamp"}
    

    How will I get time of Firebase server with javascript?

  • The.Wolfgang.Grimmer
    The.Wolfgang.Grimmer about 3 years
    How do i get the actual value if I want to return it as part of the response?
  • John T
    John T almost 3 years
    This one worked for me, the other solutions did not.
  • Miguel Jesus
    Miguel Jesus almost 3 years
    When using firestore this is the solution. The database.ServerValue.TIMESTAMP solution is for the realtime database.