Firebase Firestore get time difference between timestamp and now

Viewed 1030

I am using Firestore and I got a field with type of timestamp which record the timestamp when document was stored in the database, and it worked perfectly.

And I want to get the time different between that timestamp and current timestamp (now). How can i do that

This is the sample document I stored in the database 2020-12-11T03:01:31.674Z

enter image description here

1 Answers

As mentioned by Doug Stevenson in the comments, the field in your Firestore is a String, not a Timestamp, so you will have to convert it before you can be operated by your code. You could do something like this:

const doc = db.collection('posts').doc(id).get().then(function(doc) {
    if (doc.exists) {
       var data = doc.data();
       var createdAt = (new Date(data.first).getTime());
       var difference = Date.now() - createdAt;
       //this will be in milliseconds
       console.log(difference);
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});
Related