Categories
JavaScript Answers

How to convert a Firestore date or timestamp to a JavaScript Date?

Spread the love

Sometimes, we want to convert a Firestore date or timestamp to a JavaScript Date.

In this article, we’ll look at how to convert a Firestore date or timestamp to a JavaScript Date.

How to convert a Firestore date or timestamp to a JavaScript Date?

To convert a Firestore date or timestamp to a JavaScript Date, we use firebase.firestore.Timestamp.fromDate to convert the a date to a Firestore timestamp.

We call toDate on the timestamp object to convert it back to a JavaScript date.

For instance, we write

const t = firebase.firestore.Timestamp.fromDate(new Date());
const d = t.toDate();

to call firebase.firestore.Timestamp.fromDate with a JavaScript date object to convert it to a Firebase timestamp object.

Then we call toDate on the t timestamp object to convert it back to a JavaScript date.

Conclusion

To convert a Firestore date or timestamp to a JavaScript Date, we use firebase.firestore.Timestamp.fromDate to convert the a date to a Firestore timestamp.

We call toDate on the timestamp object to convert it back to a JavaScript date.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *