Convert date to timestamp for storing into firebase firestore in javascript

Arjen de Jong picture Arjen de Jong · Nov 26, 2018 · Viewed 34.6k times · Source

I'm currently using Math.floor(Date.now() / 1000) to get the correct timestamp format to add into a document in Firebase, however, the timestamp gets inserted as a number, and not as a timestamp.

number

I would like to have it inserted as shown below (as a timestamp, not as a number).

enter image description here

Is this possible?

Answer

Sean Stayns picture Sean Stayns · Feb 11, 2019

You can simply use the following line:

var myTimestamp = firebase.firestore.Timestamp.fromDate(new Date());

.fromDate is a static method from the static Timestamp class from Firebase.

Ref: Firebase Timestamp Doc

Update:

For cloud functions look at JGuo's comment:

If you are writing cloud functions, it becomes admin.firestore.Timestamp.fromDate() – JGuo Jan 21 at 1:56