Issue
This is related to this question: How can I get Timestamp from Firestore server without bothering for the case when device clock is out of sync with Firestore
I have understood FieldValue.serverTimestamp()
can be used to generate a Timestamp in Firestore server while performing database operations. I want to understand how I can get the timestamp from the Firestore Database in a particular device in a Date/Timestamp
format without any database related operation.
Solution
So assuming you have a database schema that looks like this:
Firestore-root
|
--- users (collection)
|
--- uidOne (document)
|
--- name: "UserOne"
|
--- creationDate: January 25, 2020 at 3:37:59 PM UTC+3 //Timestamp
To get the value of creationDate
property as a Date
object, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Date creationDate = document.getDate("creationDate");
//Do what you need to do with your Date object
}
}
});
Remember, in order to get this Date
object, the date should be set as explained in my answer from the following post:
Edit:
The question emphasized to get the Server Timestamp without performing any database related operation.
There is no way you can do this since that timestamp value is generated entirely by Firebase servers. In other words, when a write operation takes place, that timestamp is generated. You cannot simulate this on the client and it makes sense since you cannot randomly generate a server timestamp yourself. Only Firebase servers can do that. If you need a particular timestamp, you should not generate it that way. Since that property is of type Date
, you can set it with any Date you'll like. So instead of letting Firestore decide what timestamp to generate, set the Date
yourself.
Answered By - Alex Mamo
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)