I want to save the date that a post was created in Firestore but I do not want to use the System time. Rather I want to use the server timestamp for accuracy sake. So I am using FieldValue.serverTimestamp()
to get the server timestamp but the data type of my variable that holds this is Date. So How can I cast FieldValue.serverTimestamp()
to Date
?
Below is how my data class looks
data class MyModel( var timeStamp: Date,
constructor(): this(Calendar.getInstance().time, "")
}
PS: When I declare the timestamp as FieldValue in the data class, I get the error below:
java.lang.RuntimeException: No properties to serialize found on class com.google.firebase.firestore.FieldValue
You get the following error:
java.lang.RuntimeException: No properties to serialize found on class com.google.firebase.firestore.FieldValue
Because FieldValue
is not a supported data type. You should use the Date class or any other class that extends Date
class, for example Timestamp class.
How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
There is no need to do any cast. In Java there is even no need to initialize the timeStamp
field. To make it work, you should only use an annotation, as explained in my answer from the following post:
Edit:
In Kotlin, you should initialize your timeStamp
field in the constructor with a null
value like this:
data class MyModel(
@ServerTimestamp
val timeStamp: Date? = null)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With