Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 513
Alif Al-Gibran Avatar asked Apr 24 '19 06:04

Alif Al-Gibran


People also ask

How do I change the date on Kotlin?

This example demonstrates how to get the current time and date in an Android app Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What is the format of firestore timestamp?

Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.

Does firestore have timestamp?

firestore. Timestamp. A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.

How do I get the current date in Kotlin?

As Kotlin is interoperable with Java, we will be using the Java utility class and Simple Date Format class in order to get the current local date and time.


3 Answers

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

like image 58
Doug Stevenson Avatar answered Oct 19 '22 04:10

Doug Stevenson


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)
like image 10
Alif Al-Gibran Avatar answered Oct 19 '22 05:10

Alif Al-Gibran


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()
like image 3
thesamoanppprogrammer Avatar answered Oct 19 '22 05:10

thesamoanppprogrammer