如何使用 Android 在 Firestore 中添加时间戳? [英] How to add a Timestamp in Firestore with Android?
问题描述
我正在尝试使用 Firebase Firestore 在 Android 客户端中添加时间戳字段.
I am trying to add a timestamp field in an Android client with Firebase Firestore.
根据文档:
用于标记要填充服务器的日期字段的注释时间戳.如果正在写入的 POJO 包含 null@ServerTimestamp-annotated 字段,它将被替换为服务器生成的时间戳.
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.
但是当我尝试时:
@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>() {/* ... */}
这篇关于如何使用 Android 在 Firestore 中添加时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!