Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Unix timestamp to date string in Kotlin

Tags:

kotlin

How can I parse a Unix timestamp to a date string in Kotlin?

For example 1532358895 to 2018-07-23T15:14:55Z

like image 287
Chris Edgington Avatar asked Jul 23 '18 15:07

Chris Edgington


People also ask

How do you parse a date to a string in Kotlin?

Example 2: Convert String to Date using pattern formatters So, we create a formatter of the given pattern. Check all DateTimeFormatter patterns, if you're interested. Now, we can parse the date using LocalDate. parse() function and get the LocalDate object.

How do I convert a timestamp to a date?

You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.


2 Answers

The following should work. It's just using the Java libraries for handling this:

    val sdf = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
    val date = java.util.Date(1532358895 * 1000)
    sdf.format(date)
like image 154
Erik Pragt Avatar answered Oct 20 '22 03:10

Erik Pragt


Or with the new Time API:

java.time.format.DateTimeFormatter.ISO_INSTANT
    .format(java.time.Instant.ofEpochSecond(1532358895))
like image 15
jingx Avatar answered Oct 20 '22 01:10

jingx