1

To upload a custom java object to Firebase Firestore, I want to have a field created time , which will store the server timestamp when the data is created. how to do it ?

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
Shuvendu Dhal
  • 75
  • 2
  • 6

3 Answers3

2

To write a server-side timestamp in Firebase you need to use this marker value: FieldValue.serverTimestamp(). So if you want a specific field in a Java object to have this value, initialize that field to FieldValue.serverTimestamp().

public class MyObject {
    public String value;
    public Object timestamp = FieldValue.serverTimestamp();
}

I've marked the timestamp field as an Object, since (I think) it'll have a different type on initial creation than it does when you read it back from the database.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
-1

First you have to fetch your server time and then you can upload that time to firebase real time database.

your custom data class:

public class ServerTime {

    public String time;

    public ServerTime (String time) {
        this.time= time;
    }
}

ServerTime object = ServerTime(timestamp); // set your time here
DatabaseReference mRef = FirebaseDatabase.getInstance()
        .getReference("ServerTime").setValue(object);
Nik
  • 1,991
  • 2
  • 13
  • 30
  • This doesn't set the time from the server, which is what he's asking for – Gabe Sechan Jul 19 '19 at 18:39
  • To set time from server first @Shuvendu Dhal need to fetch server time and then he push that to firebase. – Nik Jul 19 '19 at 18:42
  • Which then wouldn't be accurate enough for many uses, as an unknown amount of time passed between the two events. Normal sql dbs can do this atomically, but I'm not sure firebase can – Gabe Sechan Jul 19 '19 at 18:44
-1

You connot do it from client library. You need to create a Cloud function, that triggers when value was added to firestore collection, and insert current date field to it. More about Firebase cloud functions and Firestore triggers

Marat Zangiev
  • 1,172
  • 7
  • 12