如何在Kotlin中将Firestore日期/时间戳转换为日期?

10
我正在使用Firestore,在获取来自Firestore的时间戳时遇到了麻烦。我该如何在Kotlin中将Timestamp (seconds = 1556006384,nanoseconds = 994000000)转换为日期。 我的最低SDK版本是21,因此以下代码无法使用:
val timestamp = it["time"] as com.google.firebase.Timestamp
val milliseconds = timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000
val tz = ZoneId.of("Asia/Jakarta (UTC+07:00)")
val localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), tz)

谢谢。


https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#ofEpochSecond-long- https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#plusNanos-long-https://docs.oracle.com/javase/8/docs/api/java/sql/Date.html#Date-long- - JB Nizet
4个回答

13

@wesleyfranks 调用对象的方法应该非常简单。假设您的Timestamp对象在名为“ts”的val中:ts.toDate() - Doug Stevenson

11

我正在使用这段代码:

val timestamp = it["time"] as com.google.firebase.Timestamp
val milliseconds = timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000
val sdf = SimpleDateFormat("MM/dd/yyyy")
val netDate = Date(milliseconds)
val date = sdf.format(netDate).toString()
Log.d("TAG170", date)

5

结合两个顶部的答案,我用了这个方法。

val timestamp = data[TIMESTAMP] as com.google.firebase.Timestamp
            val date = timestamp.toDate()

-1
我使用这个类来序列化时间戳。
import com.google.firebase.Timestamp

data class Article (
var createdAt: Timestamp? = Timestamp.now(),
var title: String = "",
var image: String = ""
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接