【问题标题】:Convert Cloud Firestore Timestamp to readable date将 Cloud Firestore 时间戳转换为可读日期
【发布时间】:2019-10-09 01:52:41
【问题描述】:

如何转换从 firebase firestore 数据库中检索到的时间戳并将其与当前日期和时间进行比较。

 db.collection("users").document(user.getuid).get()
                .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                    @Override
                    public void onSuccess(DocumentSnapshot documentSnapshot) {
                        String date = documentSnapshot.getData().get("last_login_date").toString();
                       
                    }
                });

将日期转换为可读并从当前时间中减去以显示天、小时和分钟的差异

日期变量的输出格式如下

Timestamp(seconds=1558532829, nanoseconds=284000000)

【问题讨论】:

标签: java firebase date google-cloud-firestore


【解决方案1】:

当您从 Cloud Firestore 中的文档中读取时间戳类型字段时,它将作为 Java 中的 Timestamp 类型对象到达。请务必阅读链接的 Javadoc 以了解更多信息。

Timestamp timestamp = (Timestamp) documentSnapshot.getData().get("last_login_date");

时间戳有两个组成部分,秒和纳秒。如果这些值对您没有用处,您可以使用其toDate() 方法将 Timestamp 转换为 Java Date 对象,但您可能会丢失一些时间戳的纳秒精度,因为 Date 对象仅使用微秒精度。

Date date = timestamp.toDate();

使用 Date 对象,您应该能够轻松使用其他日期格式化工具,例如 Android's own date formatting options。也可以使用 Date 的toMillis() 方法与System.currentTimeMillis() 中的当前时间进行比较;

见:

【讨论】:

    【解决方案2】:

    你也可以用这个。

        String date= DateFormat.getDateInstance().format(timestamp.getTime());
    

    主要用于 RecyclerView 的 Adapter 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 2018-12-09
      • 2020-02-23
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多