How do I convert a Firestore date/Timestamp to Date in Kotlin?

拜拜、爱过 提交于 2021-02-08 21:48:10

问题


i'm working with firestore, and getting stuck when i get the timestamp from firestore. how i convert this Timestamp(seconds=1556006384, nanoseconds=994000000) to Date in kotlin.

my minimum SDK is 21 so the code below doesn't work

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)

thank you.


回答1:


Call toDate() on a Firestore Timestamp object to return a Date object.




回答2:


I'm using this code:

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)



回答3:


Combined both answers on top and this is what worked for me.

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



回答4:


I used this class to serialize the Timestamp

import com.google.firebase.Timestamp

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


来源:https://stackoverflow.com/questions/55823586/how-do-i-convert-a-firestore-date-timestamp-to-date-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!