Search code examples
datekotlintimestampunix-timestamp

How to convert date string to timestamp in Kotlin?


I want to convert a date string to unix timestamp from a date string e.g. 14-02-2018

Can someone help?


Solution

  • Since JDK 8 you can do:

    val l = LocalDate.parse("14-02-2018", DateTimeFormatter.ofPattern("dd-MM-yyyy"))
    
    val unix = l.atStartOfDay(ZoneId.systemDefault()).toInstant().epochSecond
    

    Note that the example uses your system's default timezone.