首页 > 解决方案 > Firebase firestore:如何在 Android 的 Kotlin 中以秒为单位创建时间戳

问题描述

我正在尝试通过将秒数传递给它来创建一个 Firebase Firestore 时间戳对象,但它不起作用。

这是代码片段。


import com.google.firebase.Timestamp
import com.google.firebase.firestore.*


var timeStampString:String = "1438910477"
var t = timeStampString.toLong()
var ts = Timestamp(t)

我收到错误:

None of the following functions can be called with the arguments supplied
<Init>(Parcel) defined in com.google.firebase.Timestamp
<Init>(Date) defined in com.google.firebase.Timestamp

如文档中所述,我将数字作为参数传递。但它期待“包裹”或“日期”。

我究竟做错了什么?

标签: androidfirebasekotlingoogle-cloud-firestore

解决方案


正如您从链接到的 API 文档中看到的那样,构造函数需要两个数字参数,而不是一个。如果您在纳秒内没有要传递的组件,则传递 0:

var timeStampString:String = "1438910477"
var t = timeStampString.toLong()
var ts = Timestamp(t, 0)

但是,当您可以直接编码数字时,为什么要将字符串解析为数字:

var t = 1438910477
var ts = Timestamp(t, 0)

推荐阅读