I am trying to add a timestamp field in an Android client with Firebase Firestore.
According to the documentation ( https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/ServerTimestamp ):
Annotation used to mark a Date field to be populated with a server timestamp. If a POJO being written contains null for a @ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp.
But when I try it:
@ServerTimestamp
Date serverTime = null; // I tried both java.util.Date and java.sql.Date
//...
Map<String, Object> msg = new HashMap<>();
// ... more data
msg.put("timestamp", serverTime);
On the Cloud Firestore database this field is always null
.
That is not the correct way of how to add the time and date to a Cloud Firestore database. The best practice is to have a model class in which you can add a date filed of type
Date
togheter with an annotation. This is how your model class should look like:When you create on object of
YourModelClass
class, there is no need to set the date. Firebase servers will read yourdate
field as it is aServerTimestamp
(see the annotation), and it will populate that filed with the server timestamp accordingly.Another approach would be to use FieldValue.serverTimestamp() method like this:
I have similar problem, and I found this at my catlog and solved my problem
use
FieldValue.serverTimestamp()
get server timestamp