Abby
Abby

Reputation: 113

Why passing firestore timestamp to ``moment`` gives the output as invalid date?

In my project, I am using moment.js. When I pass firestore timestamp to moment it throws the output as invalid date.

Here is my code:

moment({seconds: 1663679594, nanoseconds: 42000000}).format('MM-DD-YYYY')

Please guide me on how to resolve this error.

Upvotes: 0

Views: 662

Answers (1)

Marc Anthony B
Marc Anthony B

Reputation: 4069

Firestore stores Dates as a Timestamp object. This is not the same as a Javascript Date() object. You have to convert it first into a Javascript Date object using the .toDate() method that Firestore has provided. See Sample code below:

var db = firebase.firestore();

db
.collection('collection-name')
.doc('document-id')
.get()
.then((doc) => {
    const converted = doc.data().timestamp.toDate();
    const momentDate = moment(converted).format('MM-DD-YYYY')
    console.log(momentDate);
})

For more information, you may check out this documentation.

Upvotes: 2

Related Questions