2

I save dates in a format like

this

in Cloud Firestore

How do I get it in Date format in Node.js?

  • What date format? I assume you can use moment. If yes, try `moment(value, 'DD MMMM YYYY hh:mm:ss t').format(requiredDateFormat)` – Rajesh Dec 10 '19 at 13:56
  • Possibly in ms since epoch – Nicholas Santi Dec 10 '19 at 13:57
  • Did you store the date using the Firebase sdk? – Syed Hussim Dec 10 '19 at 13:59
  • Yes, but also manually it has the same value – Nicholas Santi Dec 10 '19 at 14:00
  • @NicholasSanti This might help: https://stackoverflow.com/questions/40752287/use-moment-js-to-convert-unix-epoch-time-to-human-readable-time – Rajesh Dec 10 '19 at 14:03
  • The problem is that I don't know how to cast what I get from firestore in a date format – Nicholas Santi Dec 10 '19 at 14:04
  • 1
    Does [dateExample](https://firebase.google.com/docs/firestore/manage-data/add-data#data_types) answer your question? They are using `admin.firestore.Timestamp.fromDate(new Date('December 10, 1815'))` to store a `Timestamp` in Firestore. – sllopis Dec 10 '19 at 14:09
  • No, it doesn't I will directly save as MillisecondsSinceEpoch – Nicholas Santi Dec 10 '19 at 14:33
  • Cool, then let's try using one of the constructors that are shown [here](https://sites.google.com/site/dartlangexamples/api/dart-core/interfaces/comparable-hashable/date): `Date date = new Date.fromMillisecondsSinceEpoch(int millisecondsSinceEpoch, [bool isUtc]);` to create a Date object from `MillisecondsSinceEpoch`. Let me know how it goes. – sllopis Dec 10 '19 at 14:55
  • Just realized after posting my comment that what I shared with you right above is Dartlang; nonetheless, the idea around it would be the same for Node.js. – sllopis Dec 10 '19 at 15:06

1 Answers1

4

When you get timestamps from Firestore they are of the following type:

enter image description here

To convert this into a Node.js timestamp you can use the .toDate() function.

For example, for a document like the following:

enter image description here

We can use something like:

db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
  console.log(doc.data().[FIELD].toDate());
});

and the output will be like:

2019-12-16T16:27:33.031Z
Waelmas
  • 1,894
  • 1
  • 9
  • 19