5

I would like to set the priority of a child using the server time stamp provided by Firebase, ServerValue.TIMESTAMP:

mFirebaseref.child(userid).setPriority(ServerValue.TIMESTAMP);

But my case is inverse. I want to set negative ServerValue.TIMESTAMP to move my child to the top based on time. Is it possible to do that in Firebase without using the local time stamp System.CurrentTimeInMillis()?

I would like to do something like this:

mFirebaseref.child(userid).setPriority(-ServerValue.TIMESTAMP);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
sivaram636
  • 419
  • 3
  • 14

2 Answers2

3

On the client side, ServerValue.TIMESTAMP is an object structured like this: {.sv: "timestamp"}

So, as you know, you can't easily do what you wanted. However, there may be a different solution. If, for example, you wanted the five most recent entries, you could still set the priority by ServerValue.TIMESTAMP:

mFirebaseref.child(userid).setPriority(ServerValue.TIMESTAMP);

And then use the limitToLast() method:

Query queryRef = mFirebaseref.limitToLast(5);

To get the five most recent entries.

Also, this may help: Display posts in descending posted order

Community
  • 1
  • 1
Seamus
  • 4,539
  • 2
  • 32
  • 42
3

You are basically asking how to get negative server timestamp and it should work offline. I found a way, there is a hidden field you can use. A snippet from documentation:

Firebase offsetRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/.info/serverTimeOffset");
offsetRef.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    double offset = snapshot.getValue(Double.class);
    double estimatedServerTimeMs = System.currentTimeMillis() + offset;
  }

  @Override
  public void onCancelled(FirebaseError error) {
    System.err.println("Listener was cancelled");
  }
});
David Vávra
  • 18,446
  • 7
  • 48
  • 56
  • Link to (legacy) documentation in case anyone finds it helpful: https://www.firebase.com/docs/web/guide/offline-capabilities.html#section-latency – xsorifc28 Sep 04 '16 at 07:53