简体   繁体   中英

Convert Cloud Firestore Timestamp to readable date

How to convert timestamped retrieved from firebase firestore database and compare it with the current date and time.

 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();
                       
                    }
                });

Conver the date to readable and deduct it from the current time to show the difference in days, hours and minutes

The output of date variable is in below format

Timestamp(seconds=1558532829, nanoseconds=284000000)

When you read a timestamp type field out of a document in Cloud Firestore, it will arrive as a Timestamp type object in Java. Be sure to read the linked Javadoc to find out more about it.

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

The Timestamp has two components, seconds and nanoseconds. If those values are not useful to you, you can convert the Timestamp to a Java Date object using its toDate() method, but you might lose some of the timestamp's nanosecond precision, since Date objects only use microsecond precision.

Date date = timestamp.toDate();

With a Date object, you should be able to easily use other date formatting tools, such as Android's own date formatting options . You can also use the Date's toMillis() method to compare it with the current time from System.currentTimeMillis() ;

See:

To get the value of the date property in a correct way, please use the following lines of code:

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
            }
        }
    }
});

So having the userDate object you can comparate it with any other Date object you want.

You can also use this.

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

it mostly use in RecyclerView's Adapter class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM