Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add timestamp in Firestore documents

I'm newbie to Firestore. Firestore docs says...

Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.

Reference: https://firebase.google.com/docs/firestore/manage-data/add-data

So do I have to create key name as timestamp in document? Or created is suffice to fulfill above statement from Firestore documentation.

{     "created": 1534183990,     "modified": 1534183990,     "timestamp":1534183990 } 
like image 819
Vicky Thakor Avatar asked Aug 14 '18 17:08

Vicky Thakor


People also ask

How do you post a timestamp on firestore?

To query on this Firestore field, you need to convert the date to timestamp and then query. Store as new Date(). toISOString() i.e. "2021-07-25T17:56:40.373Z" but you won't be able to perform date range query on this.

Does firestore have timestamp?

firestore. Timestamp. A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.

How do I save a timestamp on firestore?

If you want to use server generated value which would be better so you don't depend on device time, use this: Map<String, dynamic> data = { 'name': userName, 'userUID': userUIDglobal, 'time': FieldValue. serverTimestamp(), }; Firestore. instance .

How do I get the date from firestore timestamp?

To convert a Firestore date or timestamp to a JavaScript Date, we use firebase. firestore. Timestamp. fromDate to convert the a date to a Firestore timestamp.


2 Answers

firebase.firestore.FieldValue.serverTimestamp() 

Whatever you want to call it is fine afaik. Then you can use orderByChild('created').

I also mostly use firebase.database.ServerValue.TIMESTAMP when setting time

ref.child(key).set({   id: itemId,   content: itemContent,   user: uid,   created: firebase.database.ServerValue.TIMESTAMP  }) 
like image 71
Saccarab Avatar answered Sep 28 '22 06:09

Saccarab


Use firestore Timestamp class, firebase.firestore.Timestamp.now().

Since firebase.firestore.FieldValue.serverTimestamp() does not work with add method from firestore. Reference

like image 21
johnson lai Avatar answered Sep 28 '22 05:09

johnson lai