Get ServerValue.Timestamp from Firebase in android app when data is sent

I would like to know how to use the Firebase ServerValue.TIMESTAMP method when I want to create a timestamp on the Firebase server and then return it to the local client.

In the Firebase guides, only javascript has a more detailed description of this case, but I'm having a hard time finding a way to translate this to my android app.

Thanks in advance!

+3


source to share


4 answers


Firebase.ServerValue.TIMESTAMP

is set to Map

(containing {.sv: "timestamp"}

), which tells Firebase to populate this field with the server time. When this data is read, it is the actual unix timestamp, which is 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(DatabaseError databaseError) {

    }
});

ref.setValue(ServerValue.TIMESTAMP);

      

As another example, you can see my answer to this question: Android is disabled in DataSnapshot.getValue () for timestamp

+10


source


I know this question has already been answered, but I wanted to share my version of the solution.

When I use a server timestamp, I usually need to use it more than once, i.e. I have some startTime

and endTime

that depend on the server time, where startTime

- NOW

and endTime

is X seconds / minutes / hours after startTime

, so to save a few requests on the server, I store the server time in the root child serverTime

in the database and I use its to set all dependent values.

Another thing is, due to what Firebase is working with ServerValue.Timestamp

, it ends up firing 2 events (added and modified), the first with the local timestamp and the second with the actual server timestamp. So to solve the problem of not getting the correct time, I added a simple one OnCompleteListener

.



Short code example:

import android.support.annotation.NonNull;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;

public class ServerTime {

    public interface OnTimeRetrievedListener {

        void onTimeRetrieved(Long timestamp);
    }

    private final DatabaseReference db;

    public ServerTime(DatabaseReference db) {
        this.db = db.child("serverTime");
    }

    /**
     * Gets the server timestamp in milliseconds.
     * @param listener {@link OnTimeRetrievedListener}
     */
    public void getTime(final OnTimeRetrievedListener listener) {
        if (listener == null) {
            return;
        }

        db.setValue(ServerValue.TIMESTAMP).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {

                db.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        listener.onTimeRetrieved(dataSnapshot.getValue(Long.class));
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) { }
                });

            }
        });
    }
}

      

+2


source


If you don't want to write to the database to determine the timestamp, you can get an instant approximation of it. It even works offline, which is good enough for most cases.

Read value

/.info/serverTimeOffset

      

And add it to new Date().time()

+2


source


First send the object to the Firebase server

FirebaseDatabase.getInstance().getReference("serverTimeTest").setValue(new KKModel());

Model class

class KKModel{
    public String someField = "value";
    public Object creationDate = ServerValue.TIMESTAMP;

    public String creationDate() {
        return SimpleDateFormat.getDateInstance(DateFormat.SHORT, Locale.US).format(creationDate);
    }
}

      

using

object.creationDate()

working fine test results "9/6/18"

0


source







All Articles