user7697994
user7697994

Reputation:

How to add server time using FirebaseStore timestamp?

If I'm using Firebase data-base I can set server-time as below:

user.put("time", ServerValue.TIMESTAMP);

And then update it.

But if I used the same one with FireStore it doesn't succeed, Also I don't need to implement firebase-data-base in my gradle for only this purpose.

I can see that there is ServerTimestamp.class related to FireStore but I don't know how to use it.

Thanks in advance.

Upvotes: 0

Views: 744

Answers (1)

sweggersen
sweggersen

Reputation: 2362

According to docs it would be something like this:

@ServerTimestamp Date time;

If null it will have the server-generated timestamp, so you don't need to do set the value for it.

Ref: Annotation used to mark a Date field to be populated with a server timestamp. If a POJO being written contains null for a @ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp. (https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/ServerTimestamp)

Edit:

Or when working with a map type object directly:

DocumentReference docRef = db.collection("objects").document("some-id");

// Update the timestamp field with the value from the server
Map<String,Object> updates = new HashMap<>();
updates.put("timestamp", FieldValue.serverTimestamp());

Ref: https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects

Upvotes: 1

Related Questions