Android Firestore,如何在一个文档中设置多个时间戳

时间:2018-06-10 10:26:22

标签: java android firebase google-cloud-firestore

根据官方文档doc我使用FieldValue将文档字段设置为时间戳值,我的问题是:

如何在同一文档中添加多个时间戳值,例如我需要设置 startDate endDate docTimpStamp

我使用以下代码:

@ServerTimestamp Date time;

并在添加文档时:

Map<String, Object> dataMap = new HashMap<>();
dataMap.put("startDate", FieldValue.serverTimestamp());
time.setTime (...); // here change the date to be the endDate
dataMap.put("endDate", FieldValue.serverTimestamp());
time.setTime (...); // here change the date to be the docTimeStamp
dataMap.put("docTimeStamp",FieldValue.serverTimestamp());

并且此解决方案无效,未找到的数据具有相同的值而非实时。

如何实施此流程?

1 个答案:

答案 0 :(得分:2)

我认为您正在混合使用ServerTimestamp注释和静态serverTimestamp()方法

ServerTimestamp注释“用于标记要使用服务器时间戳填充的时间戳字段。如果正在编写的POJO包含@ ServerTimestamp-annotated字段的null,则它将被服务器生成的替换时间戳“。

在您的代码中,time Date对象没有包含null的POJO。

另一方面,当您执行dataMap.put("endDate", FieldValue.serverTimestamp());时,您告诉Firestore“包含服务器生成的时间戳”,其值为endDate

因此,对于这三个值找到相同的时间是正常的,因为它们会同时写入数据库(准)。

此外,请注意,(例如)以下两行之间没有联系。

time.setTime (...); // here change the date to be the endDate
dataMap.put("endDate", FieldValue.serverTimestamp());

在第一行中,您为time设置了新值,但在第二行中未使用time。如上所述,FieldValue.serverTimestamp()未与time对象相关联。

因此,总而言之,您可能必须完全控制要编写的值(使用time.setTime(...);)并避免使用serverTimestamp()方法但使用时间对象