gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:37:49 24 4
gpt4 key购买 nike

如何转换从 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)

最佳答案

当您从 Cloud Firestore 中的文档中读取时间戳类型字段时,它将以 Timestamp 形式到达Java 中的类型对象。请务必阅读链接的 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();

中的当前时间进行比较

参见:

关于java - 将 Cloud Firestore 时间戳转换为可读日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56259128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com