Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert milliseconds to timestamp in kotlin programming

how to convert milliseconds to timestamp in kotlin.

time in milliseconds : 1575959745000 to format: dd/MM/yyyy HH:MM:ss

like image 732
user3318934 Avatar asked Feb 11 '20 11:02

user3318934


1 Answers

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.

like image 82
Joffrey Avatar answered Nov 15 '22 07:11

Joffrey