How to Add a Timestamp in Firestore With Android

How to add Firebase Timestamp when adding an object of a data class to the Firestore in Kotlin?

If you want to add a Timestamp type property using an object of Product class, please define the field in the class to be of type Date and use the annotation as below:

@ServerTimestamp
var product_added_date: Date? = null,

When you create an object of the Product class, there is no need to set the date. You don't have to pass anything to the constructor. Firebase servers will read your product_added_date field, as it is a ServerTimestamp (see the annotation), and it will populate that field with the server Timestamp accordingly.

Otherwise, create a Map and put:

"product_added_date" to FieldValue.serverTimestamp()

How to add a Timestamp in Firestore with Android?

That is not the correct way of how to add the time and date to a Cloud Firestore database. The best practice is to have a model class in which you can add a date field of type Date together with an annotation. This is how your model class should look like:

import java.util.Date;

public class YourModelClass {
@ServerTimestamp
private Date date;

YourModelClass() {}

public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}
}

When you create on object of YourModelClass class, there is no need to set the date. Firebase servers will read your date field, as it is a ServerTimestamp (see the annotation), and it will populate that field with the server timestamp accordingly.

Another approach would be to use FieldValue.serverTimestamp() method like this:

Map<String, Object> map = new HashMap<>();
map.put("date", FieldValue.serverTimestamp());
docRef.update(map).addOnCompleteListener(new OnCompleteListener<Void>() {/* ... */}

Adding Server Timestamp field to the Object which being added

Yes you can, using a Map. First of all, according to official docs it will be necessary to use an annotation that looks like this:

@ServerTimestamp Date time;

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.

This is how you can update the latestUpdateTimestamp field with the server timestamp and the challangeId with the desired value at the same time.

DocumentReference senderRef = challengeRef
.document(loggedUserEmail)
.collection("challenges_feed")
.document(callengeID);

Map<String, Object> updates = new HashMap<>();
updates.put("latestUpdateTimestamp", FieldValue.serverTimestamp());
updates.put("challangeId", "newChallangeId");
senderRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {/* ... */}

How to get server Timestamp from Firestore in an android device?

So assuming you have a database schema that looks like this:

Firestore-root
|
--- users (collection)
|
--- uidOne (document)
|
--- name: "UserOne"
|
--- creationDate: January 25, 2020 at 3:37:59 PM UTC+3 //Timestamp

To get the value of creationDate property as a Date object, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Date creationDate = document.getDate("creationDate");
//Do what you need to do with your Date object
}
}
});

Remember, in order to get this Date object, the date should be set as explained in my answer from the following post:

  • ServerTimestamp is always null on Firebase Firestore

Edit:

The question emphasized to get the Server Timestamp without performing any database related operation.

There is no way you can do this since that timestamp value is generated entirely by Firebase servers. In other words, when a write operation takes place, that timestamp is generated. You cannot simulate this on the client and it makes sense since you cannot randomly generate a server timestamp yourself. Only Firebase servers can do that. If you need a particular timestamp, you should not generate it that way. Since that property is of type Date, you can set it with any Date you'll like. So instead of letting Firestore decide what timestamp to generate, set the Date yourself.

Add timestamp in Firestore documents

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
})

How to store timestamp on firestore using android EditText and DateTimePicker Dialog

you can save Date object as timestamp
in your case , you can parse the string to date object and save it directly as field in firestore document , for example you could do something like this :-

first : convert the valid date string to date object

static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
public Date getDateFromString(String datetoSaved){

try {
Date date = format.parse(datetoSaved);
return date ;
} catch (ParseException e){
return null ;
}

}

then save the date object as field in firestore document

public void savetoDatabase(){

FirebaseFirestore db = FirebaseFirestore.getInstance();

Map<String,Object> addAnimal = new HashMap<>();
addAnimal.put("dob",getDateFromString("2017-10-15T09:27:37Z"));

db.collection("users").document("animals").set(addAnimal);

}

you can choose any other format for more info check how to parse dates and how the java.util.Date object works .

if you runs the above code the date will saved as Timestamp in firestore document

Sample Image

How to save timestamp in Firestore?

To solve this, you should remove the Date time as the argument of your constructor. Your constructor should be like this:

public messgaesDataClass(String messageText, int messageStatus, String messagefrom) {
this.messageText = messageText;
this.messageStatus = messageStatus;
this.messagefrom = messagefrom;
}

There is no need to initialize the time object in your constructor. Firebase servers will read your time field as it is a ServerTimestamp (because of the annotation), and it will populate that filed with the server timestamp accordingly.

How to display Firestore timestamp(Date and Time) in a RecyclerView

If Timestamp is firebase package, then you can go with Timestamp#toDate() function

model.gettTimestamp().toDate().toString() which should give you whole date

Android studio firestore timestamp comparing to currentLocalTime

In firestore timestamp, we have an API getSeconds(). This API return time in second (long data type).

Timestamp timestamp = (Timestamp) document.getData().get("createdAt");
Long tsLong = System.currentTimeMillis()/1000;
long result = tsLong - timestamp.getSeconds();


Related Topics



Leave a reply



Submit