简体   繁体   中英

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

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.

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

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)

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()

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 = ""
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM