Firebase: Store server timestamp when document created
At the time of writing this, the accepted solution does not work. The expression firebase.firestore.FieldValue.serverTimestamp()
is no longer valid. The Timestamp
is now direcly inside firestore
.
Thus, to get the current server time in seconds you can write
require('firebase-admin').firestore.Timestamp.now()._seconds
It looks like you're creating a document in Firestore, but trying to get a timestamp from the Realtime Database, which is a different Firebase Product.
Here's how to use Firestore's timestamp (Updated on Feb 2019):
firestore().collection("item")
.add({...item, created: firebase.firestore.Timestamp.fromDate(new Date()) })
This solution worked for me (on March 2020):
Firestore.instance.collection("item").add({...other items, 'created': FieldValue.serverTimestamp()});
The result in Cloud Firestore is:
Cloud Firestore Result