Skip to content Skip to sidebar Skip to footer

How To Get A Javascript Date Object From The New `firebase.firestore.fieldvalue.servertimestamp()`

Firebase Firestore recently changed how they manage timestamps, and I'm unable to retrieve a date object from the timestamp. How do I get a date object from the new firebase.firest

Solution 1:

You just need to do this:

yourFirestoreTimestamp.toDate()

If you look at the Timestamp object in the console you'll see that .toDate()is a function available by default on each Timestamp.

--

However, please note that when you haven't synced with Firestore yet FieldValue.serverTimestamp() gives nothing of value.

Only after you have synced with Firestore and the data is fetched again, the prop will be changed from serverTimestamp → to Timestamp

You'll also see much more information saved in a Timestamp object:

preview of Timestamp in the console

Solution 2:

firebase.firestore.FieldValue.serverTimestamp() just returns a sentinel object that you use when writing a field to a document. It indicates the server should replace it with an actual Timestamp object. serverTimestamp() itself does not contain any date information, and you can't convert it to a date.

When you write the sentinel value to a document, and read it back out, it will become a Timestamp type object, which you can convert to a native Date object with its toDate() method

Solution 3:

At last, I could get what I need

new Date(firebase.firestore.Timestamp.now().seconds*1000).toLocaleDateString()

Post a Comment for "How To Get A Javascript Date Object From The New `firebase.firestore.fieldvalue.servertimestamp()`"