mesqueeb
mesqueeb

Reputation: 6354

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.firestore.FieldValue.serverTimestamp()?

Upvotes: 17

Views: 24690

Answers (4)

Manbus
Manbus

Reputation: 1026

If you're looking for a solution in 2022, here you go:

admin.firestore.FieldValue.serverTimestamp()

You'll need to import admin for it to work like this:

const admin = required("firebase-admin");

*Please note this only works in a node environment ie in cloud functions.

Upvotes: -1

Nagibaba
Nagibaba

Reputation: 5418

At last, I could get what I need

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

Upvotes: 12

mesqueeb
mesqueeb

Reputation: 6354

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

Upvotes: 46

Doug Stevenson
Doug Stevenson

Reputation: 317948

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

Upvotes: 18

Related Questions