user3537089 user3537089 - 4 years ago 3472
Java Question

Retrieve ServerValue.Timestamp from Firebase in Android app, when data is sent

I would like to know how to use Firebase's ServerValue.TIMESTAMP method, when I want to create a timestamp at the Firebase server, and then retrieve it to the local client.

In Firebase guides, only javascript has a more detailed description of this case, but I'm having a hard time figureing how to translate this in to my Android appliction.

Thanks in advance!

Answer Source

Firebase.ServerValue.TIMESTAMP is set as a Map (containing {.sv: "timestamp"}) which tells Firebase to populate that field with the server's time. When that data is read back, it is the actual unix time stamp which is a Long.

Something like this will work:

Firebase ref = new Firebase("https://YOUR-FIREBASE.firebaseio.com");    

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        Long timestamp = (Long)(snapshot.getValue());
        System.out.println(timestamp);
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

ref.setValue(ServerValue.TIMESTAMP);

For another example, you can see my answer to this question: Android chat crashes on DataSnapshot.getValue() for timestamp

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download