Reputation: 2175
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
Upvotes: 5
Views: 3980
Reputation: 111
model class
data class MyModel(
@get: PropertyName("timestamp") @set: PropertyName("timestamp") var timestamp: Date= Date()
)
when initialize it;
val model = MyModel().apply{
this.timestamp to FieldValue.serverTimestamp()
}
Upvotes: 0
Reputation: 138969
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)
Upvotes: 8
Reputation: 55
You can make use of an object to hold this value and later while using this value check the type of the object and make use of it. As of my knowledge the datatype returned is Long and you have to convert it manually to Data if you need.
The code for this will look like this,
replace this
data class MyModel( var timeStamp: Date,
with
data class MyModel( var timeStamp: Object,
And when using this timeStamp
anywhere check it's type.
In java it will look like
if (timeStamp instanceof Long) {
// change Long to Date
//do this
}else{
//do something else
}
set the value for timeStamp
as FieldValue.serverTimestamp()
itself.
Upvotes: 0