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:
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))
})
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?
You can use toDate() function along with toDateString() to display the date part alone.
const date = dateCreated.toDate().toDateString()
//Example: Friday Nov 27 2017
Suppose you want only the time part then use the toLocaleTimeString()
const time = dateCreated.toDate().toLocaleTimeString('en-US')
//Example: 01:10:18 AM, the locale part 'en-US' is optional
You can use Timestamp.fromDate
and .toDate
for converting back and forth.
// Date to Timestamp
const t = firebase.firestore.Timestamp.fromDate(new Date());
// Timestamp to Date
const d = t.toDate();