问题
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 ServerValue.TIMESTAMP
which is both are used to save data. I don't want to save data I just want to get the server time.
Is there a static way like FirebaseFirestore.getInstance().getServerTime()
?
回答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 = new Date();
Date dateEnd = new Date();
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= new HashMap<>();
map.put("startTime", (new Date()).getTime());
db.collection(userdata).document(userid).set(map);
// At the time of retrieving:
db.collection(userdata).document(userid).get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = 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
回答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.
来源:https://stackoverflow.com/questions/61161410/get-current-server-date-and-time-in-firebase-firestore