17

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()?

mesqueeb
  • 5,277
  • 5
  • 44
  • 77

4 Answers4

46

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

mesqueeb
  • 5,277
  • 5
  • 44
  • 77
  • 2
    This doesn't work with return value of `firebase.firestore.FieldValue.serverTimestamp()`, which is not a Timestamp type object. The returned sentinel value will become a timestamp only after the document value is actual written to the document, as I've described in my answer here. – Doug Stevenson Jan 02 '20 at 18:51
  • @DougStevenson thanks for the info. I have updated my answer to include the info in your comment. – mesqueeb Jan 03 '20 at 01:35
18

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

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
12

At last, I could get what I need

new Date(firebase.firestore.Timestamp.now().seconds*1000).toLocaleDateString()
Nagibaba
  • 4,218
  • 1
  • 35
  • 43
  • 3
    Thanks. I had to add a underscore (`_`) to the `seconds` key to make it work: `new Date(firebase.firestore.Timestamp.now()._seconds*1000).toLocaleDateString()` – allegutta Feb 05 '21 at 21:15
-1

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.

Manbus
  • 706
  • 4
  • 9
  • not clear that you're talking about the admin-sdk, nor where `admin` comes from. Newer devs will be very confused about this post. Also better mention this is not usable in the browser, but only in a Node environment, like cloud functions. – mesqueeb Mar 26 '22 at 06:01
  • How to convert it to Date? – Roman Soviak Aug 04 '22 at 11:12