将 Cloud Firestore 时间戳转换为可读日期

Ome*_*hel 4 java date firebase google-cloud-firestore

如何转换从 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();
                       
                    }
                });
Run Code Online (Sandbox Code Playgroud)

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

日期变量的输出采用以下格式

Timestamp(seconds=1558532829, nanoseconds=284000000)
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 5

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

Timestamp timestamp = (Timestamp) documentSnapshot.getData().get("last_login_date");
Run Code Online (Sandbox Code Playgroud)

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

Date date = timestamp.toDate();
Run Code Online (Sandbox Code Playgroud)

有了 Date 对象,您应该能够轻松使用其他日期格式化工具,例如Android 自己的日期格式化选项。您还可以使用 Date 的toMillis()方法将其与当前时间进行比较System.currentTimeMillis()

看: