Noman Ali
Noman Ali

Reputation: 3340

How do i get negative timestamp to save in firebase - Javascript

Searched everywhere but could not found any solution or answer. I can get timestamp using following code:

var timestamp = firebase.database.ServerValue.TIMESTAMP;

But I want to store negative timestamp for sorting purposes. How do I get it?

When I try to multiply it with -1 it gives NaN error because it's an object. How?

Upvotes: 1

Views: 1283

Answers (1)

JeffD23
JeffD23

Reputation: 9308

Negative timestamps are useful when the dataset is too large to reverse client-side.

The Firebase server timestamp is an object that gets converted to a number after the data is saved. Therefore, you need to save the postive timestamp, then convert it to a negative timestamp after the initial push. Here is a verified working example.

  let timestamp = firebase.database.ServerValue.TIMESTAMP
  const promise = firebase.database().ref().child('posts').push({ timestamp })
  const key = promise.key

  promise.then(_ => {
    const postRef = firebase.database().ref('/posts/' + key)
    postRef.once('value').then(function(snapshot) {
      timestamp = snapshot.val().timestamp * -1
      postRef.update({ timestamp })
    });
  })

Upvotes: 5

Related Questions