簡體   English   中英

將 Cloud Firestore 時間戳轉換為可讀日期

[英]Convert Cloud Firestore Timestamp to readable date

如何轉換從 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 中的文檔中讀取時間戳類型字段時,它將作為 Java 中的時間戳類型對象到達。 請務必閱讀鏈接的 Javadoc 以了解更多信息。

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

時間戳有兩個組成部分,秒和納秒。 如果這些值對您沒有用處,您可以使用其toDate()方法將 Timestamp 轉換為 Java Date 對象,但您可能會失去一些時間戳的納秒精度,因為 Date 對象僅使用微秒精度。

Date date = timestamp.toDate();

使用 Date 對象,您應該能夠輕松使用其他日期格式化工具,例如Android 自己的日期格式化選項 您還可以使用 Date 的toMillis()方法將其與System.currentTimeMillis()的當前時間進行比較;

看:

要以正確的方式獲取date屬性的值,請使用以下代碼行:

db.collection("users").document(user.getuid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Date userDate = document.getDate("date");

                //Do what you need to with the userDate object
            }
        }
    }
});

因此, userDate對象,您可以將其與所需的任何其他Date對象進行比較。

你也可以使用這個。

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

它主要用於 RecyclerView 的 Adapter 類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM