How do I convert a Firestore date/Timestamp to a JS Date()?
How to convert Unix timestamp to JavaScript Date object.
var myDate = a.record.dateCreated;
new Date(myDate._seconds * 1000); // access the '_seconds' attribute within the timestamp object
The constructor for a JavaScript's Date
doesn't know anything about Firestore's 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
.
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();