问题描述
我正在尝试使用Firebase Firestore在Android客户端中添加时间戳字段.
I am trying to add a timestamp field in an Android client with Firebase Firestore.
根据文档:
但是当我尝试时:
@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);
在Cloud Firestore数据库上,此字段始终为null
.
On the Cloud Firestore database this field is always null
.
推荐答案
这不是将时间和日期添加到Cloud Firestore数据库的正确方法.最佳实践是拥有一个模型类,在其中可以添加类型为Date
的日期字段以及注释.这是您的模型类的外观:
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;
}
}
在YourModelClass
类的对象上创建时,无需设置日期. Firebase服务器将读取您的date
字段,因为它是一个ServerTimestamp
(请参见注释),并且它将相应地使用服务器时间戳填充该字段.
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.
另一种方法是使用 FieldValue.serverTimestamp()方法:
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>() {/* ... */}
这篇关于在Firebase Firestore上ServerTimestamp始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!