2

I'm creating this post as I can't solve my problem with existing ones.

I'm saving the current time on Firestore with :

Map<String, Object> docData = new HashMap<>();
            docData.put("Starting date", new Timestamp(new Date()).toDate());
            docData.put("Quantification", 3.14569);


            userManager.getUsersCollection().document(userManager.getCurrentUser().getUid())
                    .collection("habits")
                    .document(selectedHabit)
                    .set(docData)

Then, I would like to get back the timestamp and use it to count since how many days it's been created. I'm stuck here. The only way I found to access specific data of a document is by doing this :

userManager.getLoggedUserHabitsSubCollection()
    .get()
    .addOnCompleteListener(new OnCompleteListener < QuerySnapshot > () {@
        Override
        public void onComplete(@NonNull Task < QuerySnapshot > task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document: task.getResult()) {
                    Log.d("test", document.getId() + " => " + document.getData() + " => " + document.get("Starting date"));
                }
            } else {}
        }
    });

with "document.get("Starting date") I can access my saved date, that's the only thing that I was able to make work to do so. Now I would like to be able to display this Object in a string, and to check differences between dates to know how much time have passed. And here I'm stuck. I see a lot of different answers on forums, like using .toDate() for example, but when I write document.getData().toDate(), it's in red. I tried a lot of things with different ways of writing it, it's always in red and I can't make it work. Any help appreciated.

Tarik Huber
  • 7,061
  • 2
  • 12
  • 18
Tritize
  • 31
  • 8

1 Answers1

2

I see a lot of different answers on forums, like using .toDate() for example, but when I write document.getData().toDate(), it's in red.

DocumentSnapshot#getData() method returns an object of type Map<String, Object>. So there is no way you can add a call to .toDate() on such an object. If you need to get the value of a specific field as a Date object, then you should use the getDate(String field) method, which:

Returns the value of the field as a Date.

Or DocumentSnapshot#getTimestamp(String field) method which:

Returns the value of the field as a com.google.firebase.Timestamp.

Once you have the Date object, you can then calculate the difference between two Java date instances.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thanks it might sounds silly but I was confused about this, your answer help me I finally used "document.getTimestamp("myString")" to make it work, had no idea of this "getDate" or "getTimestamp" feature – Tritize Sep 20 '21 at 07:00
  • Good to hear that you made it work. – Alex Mamo Sep 20 '21 at 07:34