18

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

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

Chris Edgington
  • 2,937
  • 5
  • 23
  • 42
  • What did you try so far? The best that comes to my mind is already answered here: https://stackoverflow.com/questions/3371326/java-date-from-unix-timestamp – Roland Jul 23 '18 at 15:22
  • @Roland he was interested in Kotlin solution – Ewoks Dec 04 '18 at 10:01
  • @Roland Because that solved the problem for me, and also I wasn't aware you could call pure java libraries from Kotlin like that. However, have changed to the `java.time` method. – Chris Edgington Dec 04 '18 at 15:57
  • That's fine. Admittedly I assumed that as known... but good to know... will take that into account in future answers/comments. :-) – Roland Dec 04 '18 at 16:08

2 Answers2

26

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)
Erik Pragt
  • 13,513
  • 11
  • 58
  • 64
  • If you can, rather use the classes and utils of `java.time`... even though for such a simple sample it doesn't really matter... – Roland Dec 04 '18 at 12:39
  • This answer is giving me a wrong date time...The accepted answer gives me the correct date time, but it requires min API 26... – Ramiro G.M. May 04 '23 at 19:03
16

Or with the new Time API:

java.time.format.DateTimeFormatter.ISO_INSTANT
    .format(java.time.Instant.ofEpochSecond(1532358895))
jingx
  • 3,698
  • 3
  • 24
  • 40