Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: Store server timestamp when document created

when I use this code :

firestore().collection("item").add({...item, created: firebase.database.ServerValue.TIMESTAMP})

It creates entry {".sv" : "timestamp"} <-- actual word "timestamp"

like image 401
rendom Avatar asked Dec 25 '17 10:12

rendom


4 Answers

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()) })
like image 147
Rosário Pereira Fernandes Avatar answered Oct 22 '22 05:10

Rosário Pereira Fernandes


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
like image 28
Ali Nem Avatar answered Oct 22 '22 04:10

Ali Nem


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

like image 6
Marcel Avatar answered Oct 22 '22 04:10

Marcel


I use the official suggestion as here below:

updateDoc(doc.ref, {
timestamp: serverTimestamp()
});
like image 1
chx Avatar answered Oct 22 '22 06:10

chx