How do I convert a Firestore date/Timestamp to a JS Date()?

blueether picture blueether · Sep 9, 2018 · Viewed 52.1k times · Source

I am trying to convert the below date to a javascript Date() object. When I get it back from the server, it is a Timestamp object,

Screenshot from Firebase Firestore console:

enter image description here

When I try the following on a list of objects returned from firestore:

  list.forEach(a => {
    var d = a.record.dateCreated;
    console.log(d, new Date(d), Date(d))
  })

I get this output: enter image description here

Clearly the Timestamps are all different, and are not all the same date of Sept 09, 2018 (which happens to be today). I'm also not sure why new Date(Timestamp) results in an invalid date. I'm a bit of a JS newbie, am I doing something wrong with the dates or timestamps?

Answer

Doug Stevenson picture Doug Stevenson · Sep 9, 2018

The constructor for a JavaScript Date doesn't know anything about Firestore Timestamp objects - it doesn't know what to do with them.

If you want to convert a Timestamp to a Date, use the toDate() method on the Timestamp.