Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class

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

like image 381
Ilo Calistus Avatar asked Mar 04 '23 13:03

Ilo Calistus


1 Answers

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:

  • ServerTimestamp is always null on Firebase Firestore

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)
like image 119
Alex Mamo Avatar answered Apr 07 '23 14:04

Alex Mamo