'How to add Timestamp in firebase cloud functions

I am trying to add Timestamp in Firestore document on Firebase Cloud functions.

I had tried firestore.Timestamp.fromDate(new Date()), but its not working.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firestore = admin.firestore();
const createdAt = firestore.Timestamp.fromDate(new Date());
console.log(createdAt);

Value of createdAt should return the server timestamp, but its throwing error.



Solution 1:[1]

This line of code has a syntax error in it. It's not valid JavaScript:

const createdAt: firestore.Timestamp.fromDate(new Date());

It looks like you meant to write this:

const createdAt = firestore.Timestamp.fromDate(new Date());

Solution 2:[2]

I personallly used const timestamp = new Date().getTime(); then saved it to the firstore document and it worked.

Solution 3:[3]

When using cloud function hooks specifically functions.auth.user().onCreate((user) => {}) I use the user.metadata.creationTime to get the exact creation time without having to go into timezone and date/time issues.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Doug Stevenson
Solution 2 adeboye0
Solution 3 Ziad Alame