Skip to content Skip to sidebar Skip to footer

Get Current Server Date And Time In Firebase Firestore

I want to get my server time in Firebase Firestore so I can use it for my countdown logic. I can't find anywhere and mostly they suggest to use FiedValue.serverTimeStamp or ServerV

Solution 1:

As per said by the @Doug there is no way of getting just only time from Firebase. However there are many round-ways for the same.

Firstly, you can use the count-down using the device of the app user since all the time in today era is synced with satellite. This can be done using:

Date dateStart = newDate();
Date dateEnd = newDate();
System.out.println(dateEnd.getTime() - dateStart.getTime()/1000);

Secondly, create an object in firebase for the starting time (for particular user) and then when the countdown is over then count the difference between the current time and the time uploaded in database.

FirebaseFirestore db = FirebaseFirestore.getInstance();

// At the time of setting.Map<String, Object> map= newHashMap<>();
map.put("startTime", (newDate()).getTime());

db.collection(userdata).document(userid).set(map);

// At the time of retrieving:

db.collection(userdata).document(userid).get()
.addOnCompleteListener(newOnCompleteListener<DocumentSnapshot>() {
    @OverridepublicvoidonComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshotdocument = task.getResult();
            if (document.exists()) {
                // Here you can get the time..
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

Now if you don't like any of the above method then you can file a support request for time at https://firebase.google.com/support

Solution 2:

There is no provided method to get the actual server time.

Server timestamps are just token values on the client that are give a final value when they reach Firestore. The best you can do is write a server timestamp to a field in a document, then read the doucument back from Firestore after field has a value. Bear in mind that the timestamp will be "late" at that point, because of the time it takes your code to actually write and read the data. You have no guarantee how long that process will take.

For a more details explanation of how server timestamps work, read this article.

Post a Comment for "Get Current Server Date And Time In Firebase Firestore"