how to convert milliseconds to timestamp in kotlin.
time in milliseconds : 1575959745000 to format: dd/MM/yyyy HH:MM:ss
EDIT: now, there is the kotlinx-datetime library
There is no pure Kotlin support for dates at the moment, only durations. You will have to rely on the target platform's facilities for date/time parsing and formatting.
Note that, whatever platform you're targeting, it doesn't really make sense to convert a millisecond epoch to a formatted date without defining the timezone.
If you're targeting the JVM, then you can use the java.time
API this way:
// define once somewhere in order to reuse it
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
// JVM representation of a millisecond epoch absolute instant
val instant = Instant.ofEpochMilli(1575959745000L)
// Adding the timezone information to be able to format it (change accordingly)
val date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
println(formatter.format(date)) // 10/12/2019 06:35:45
If you're targeting JavaScript, things get trickier. You can do the following to use some sort of default time zone, and some close-enough format (defined by the locale "en-gb"
):
val date = Date(1575959745000)
println(date.toLocaleString("en-gb")) // 10/12/2019, 07:35:45
You have ways to specify the timezone according the standard JS API for Date.toLocaleString()
. But I haven't dug much into the details.
As for native, I have no idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With