14

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,384
  • 4
  • 20
  • 34
  • 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

24

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
  • 11,804
  • 10
  • 44
  • 55
  • 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
11

Or with the new Time API:

java.time.format.DateTimeFormatter.ISO_INSTANT
    .format(java.time.Instant.ofEpochSecond(1532358895))
jingx
  • 2,853
  • 2
  • 19
  • 32