3

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(),
    )
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Codist
  • 737
  • 8
  • 23

1 Answers1

4

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()
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Awesome, well explained. it did great. I used it to add the timestamp and also displayed it back in my app. Just curious if I can get it back in a custom format? Suppose I want to show it as dd/mm/yy. Thanks. – Codist Aug 01 '21 at 13:49
  • 1
    Since it's a Java Date type property you can [format it as you want](https://stackoverflow.com/questions/4772425/change-date-format-in-a-java-string). – Alex Mamo Aug 01 '21 at 13:52