Reputation: 33
I am using an API from USGS website.
"properties": {
"mag": 3.2,
"place": "Puerto Rico region",
"time": 1164925597950,
"updated": 1415323859614,
"tz": null
}
The time is in milliseconds. I want to extract date & time from these milliseconds. How can I do this in Kotlin?
Upvotes: 3
Views: 3293
Reputation: 29884
From API level 26 on (Android) or if the JVM is your target, you can use the Java 8 Date API:
val date = Instant
.ofEpochMilli(1164925597950)
.atZone(ZoneId.systemDefault()) // change time zone if necessary
.toLocalDateTime()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
println(formatter.format(date)) // 2006-11-30 23:26
Below API level 26:
val date = Date(1164925597950)
val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm")
println(formatter.format(date)) // 2006-11-30 23:26
Upvotes: 1
Reputation: 976
Just pass your milliseconds to Date Constructor Date(timeinMillis)
it will return the date.
Upvotes: 0
Reputation: 313
import java.text.SimpleDateFormat
import java.util.Date
fun convertLongToTime (time: Long): String {
val date = Date(time)
val format = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
return format.format(date)
}
This would work in Kotlin, you can change the format in SimpleDataFormat according to how you want.
Upvotes: 4
Reputation: 713
Here is the way i use in Java. You just simply change it for kotlin.
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(dateInMillis)));
Upvotes: 0