'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
Solution 1:[1]
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.
Solution 2:[2]
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()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adhithya G Nair |
| Solution 2 | Abdulkerim Yıldırım |
