ServerTimestamp is always null on Firebase Firestore

前端 未结 4 2006
攒了一身酷
攒了一身酷 2020-11-22 07:58

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

According to the documentation:

Annotation used to mark a D

相关标签:
4条回答
  • 2020-11-22 08:42

    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>() {/* ... */}
    
    0 讨论(0)
  • 2020-11-22 08:56

    use FieldValue.serverTimestamp() get server timestamp

    Map<String, Object> msg = new HashMap<>();
    msg.put("timestamp", FieldValue.serverTimestamp());
    
    0 讨论(0)
  • 2020-11-22 09:00

    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.

    0 讨论(0)
  • 2020-11-22 09:02

    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 讨论(0)
提交回复
热议问题