【问题标题】:How to add a Timestamp in Firestore with Android?如何使用 Android 在 Firestore 中添加时间戳?
【发布时间】:2018-07-06 14:18:09
【问题描述】:

我正在尝试使用 Firebase Firestore 在 Android 客户端中添加时间戳字段。

根据documentation

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

但是当我尝试时:

@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

【问题讨论】:

  • 您注释的是局部变量,而不是 POJO 字段。两者有很大区别。
  • 通过该注释,您告诉 Firestore 转换,当使用 POJO 时,必须将 Store DB 中具有相同名称的字段从 Firestore tiemstamp 转换为最新。您必须先设置时间戳。 Firestore 不会自动设置时间戳,因为 Firestore 在创建时不知道应该何时设置时间戳?在更新?在特定领域写?看看阿里的答案

标签: java android firebase google-cloud-firestore


【解决方案1】:

这不是将时间和日期添加到 Cloud Firestore 数据库的正确方法。最佳实践是有一个模型类,您可以在其中添加Date 类型的日期字段和注释。你的模型类应该是这样的:

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(请参阅注释),并且会使用服务器时间戳相应地填充该字段。

另一种方法是像这样使用FieldValue.serverTimestamp() 方法:

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

【讨论】:

  • 一切都好吗?我可以帮助您了解其他信息吗?
  • 太棒了!现在它正在工作,有效地,在 pojo 类中编写这个字段就可以了。谢谢。
  • 我得到 null Logger.info("Date", new YourModelClass().getDate() + "");
  • 添加一个包含 mcve 的新问题,以便我和其他用户也可以帮助您。
  • 我没有做任何事情,我只是复制了上面的模型并在日志上打印了日期 Like Log.d("Date",new YourModelClass().getDate()+"") 但我得到了 null
【解决方案2】:

使用FieldValue.serverTimestamp()获取服务器时间戳

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

【讨论】:

  • 乐于助人:)
【解决方案3】:

我有类似的问题,我在我的目录中找到了这个并解决了我的问题

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

【讨论】:

    【解决方案4】:

    我也遇到过类似的问题,

    我得到了异常...has type java.sql.Timestamp, got java.util.Date ...,所以我只是将类型从Timestamp 替换为Date(来自java.util.Date)并且工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      相关资源
      最近更新 更多