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

Viewed 827

Following is the sample of my data class to add product details to the Firestore, I wanted to add Firebase timestamp to know when the item was added. Even though I do not know how to do it, I tried to like the following but I am getting an error.

Note: I know how to add Timestamp to Firestore and I have done that using "timestamp" to FieldValue.serverTimestamp() when adding a Hashmap. I am having trouble when it's part of an object of my data class.

    @Parcelize
data class Product(
    val user_id: String = "",
    val mrp: String= "0.00",
    val price: String = "0.00",
    val description: String = "",
    val stock_quantity: String = "",
    val image: String = "",
    val product_added_date: FieldValue? = null,
) : Parcelable

The object of the product to add to Firestore.

val product = Product(
        FirestoreClass().getCurrentUserID(),
        et_product_mrp.text.toString(),
        et_product_price.text.toString(),
        et_product_description.text.toString().trim { it <= ' ' },
        et_product_quantity.text.toString().trim { it <= ' ' },
        mProductImageURL!!,,
        et_product_delivery_charge.text.toString().trim { it <= ' ' },
        imageURL.size,
        FieldValue.serverTimestamp(),
    )
1 Answers

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()
Related