9
votes

I am trying to add a timestamp field in an Android client with Firebase Firestore.

According to the documentation:

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.

4
You're annotating a local variable, not a POJO field. There is a big difference between the two. - Doug Stevenson
With that anotation you are telling Firestore convertion that when the POJO is used the field with that equivalent name in the Store DB must be transformed from Firestore tiemstamp to date. You have to set the timestamp first. Firestore wont set the Timestamp automatically because Firestore doesn't know when the timestamp should be set, on creation? on update? on an specific field write? Look at the Ali answer - cutiko

4 Answers

18
votes

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 field of type Date together with an annotation. This is how your model class should look like:

import java.util.Date;

public class YourModelClass {
    @ServerTimestamp
    private Date date;

    YourModelClass() {}

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

When you create on object of YourModelClass class, there is no need to set the date. Firebase servers will read your date field, as it is a ServerTimestamp (see the annotation), and it will populate that field with the server timestamp accordingly.

Another approach would be to use FieldValue.serverTimestamp() method like this:

Map<String, Object> map = new HashMap<>();
map.put("date", FieldValue.serverTimestamp());
docRef.update(map).addOnCompleteListener(new OnCompleteListener<Void>() {/* ... */}
6
votes

use FieldValue.serverTimestamp() get server timestamp

Map<String, Object> msg = new HashMap<>();
msg.put("timestamp", FieldValue.serverTimestamp());
1
votes

I have similar problem, and I found this at my catlog and solved my problem

firebaseFirestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
                .setTimestampsInSnapshotsEnabled(true)
                .build();
firebaseFirestore.setFirestoreSettings(settings);
0
votes

I had a similar problem,

I was getting the exception ...has type java.sql.Timestamp, got java.util.Date ..., so I just replace the type from Timestamp to Date ( from java.util.Date) and worked fine.