将数据 class 的对象添加到 Kotlin 中的 Firestore 时如何添加 Firebase 时间戳?

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

以下是我的数据示例 class 将产品详细信息添加到 Firestore,我想添加 Firebase 时间戳以了解添加项目的时间。尽管我不知道该怎么做,但我尝试点赞以下内容,但出现错误。

注意:我知道如何将时间戳添加到 Firestore,我在添加 Hashmap 时使用 "timestamp" to FieldValue.serverTimestamp() 做到了这一点。当它是我的数据对象的一部分时我遇到了麻烦 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

要添加到 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(),
    )

如果要使用 Product class 的对象添加时间戳类型 属性,请将 class 中的字段定义为类型 Date 并使用如下注释:

@ServerTimestamp
var product_added_date: Date? = null,

创建Product对象时class,不需要设置日期。您不必将任何内容传递给构造函数。 Firebase 服务器将读取您的 product_added_date 字段,因为它是一个 ServerTimestamp(请参阅注释),并且会相应地使用服务器时间戳填充该字段。

否则,创建一个地图并放置:

"product_added_date" to FieldValue.serverTimestamp()