Reputation: 487
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)
Upvotes: 4
Views: 11577
Reputation: 23
You can also use this.
String date= DateFormat.getDateInstance().format(timestamp.getTime());
it mostly use in RecyclerView's Adapter class.
Upvotes: 0
Reputation: 317467
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:
Upvotes: 5