如何将FieldValue.serverTimestamp()转换为Kotlin/Java Date类 [英] How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class

查看:105
本文介绍了如何将FieldValue.serverTimestamp()转换为Kotlin/Java Date类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存在Firestore中创建帖子的日期,但是我不想使用系统时间.而是为了准确性起见,我想使用服务器时间戳.因此,我正在使用FieldValue.serverTimestamp()来获取服务器时间戳,但是保存此时间戳的变量的数据类型是Date.那么如何将FieldValue.serverTimestamp()强制转换为Date?

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:当我在数据类中将时间戳声明为FieldValue时,出现以下错误:

PS: When I declare the timestamp as FieldValue in the data class, I get the error below:

java.lang.RuntimeException:在类上找不到要序列化的属性 com.google.firebase.firestore.FieldValue

java.lang.RuntimeException: No properties to serialize found on class com.google.firebase.firestore.FieldValue

推荐答案

您会收到以下错误:

java.lang.RuntimeException:在com.google.firebase.firestore.FieldValue类上找不到要序列化的属性

java.lang.RuntimeException: No properties to serialize found on class com.google.firebase.firestore.FieldValue

因为FieldValue不是受支持的数据类型 .您应该使用日期类或扩展Date类的任何其他类,例如时间戳类.

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.

如何将FieldValue.serverTimestamp()强制转换为Kotlin/Java日期类

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

无需执行任何强制转换.在Java中,甚至不需要不需要初始化timeStamp字段.要使其正常工作,您应该仅使用注释,如以下帖子中我的回答所述:

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:

在Kotlin中,您应使用如下所示的null值初始化构造函数中的timeStamp字段:

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)

这篇关于如何将FieldValue.serverTimestamp()转换为Kotlin/Java Date类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆