How to convert date string to timestamp in Kotlin?

69,168

Solution 1

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.

Solution 2

use this to convert the date string to UNIX timestamp

val date = SimpleDateFormat("dd-MM-yyyy").parse("14-02-2018")
println(date.time)

Solution 3

For backward compatibility use ThreeTenABP library but a better solution from Android itself will be enabling support https://developer.android.com/studio/write/java8-support#library-desugaring

Once enabled you can now parse String date to any valid format pattern

LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE_TIME).format(
        DateTimeFormatter.ofPattern("MMM. dd, yyyy")
Share:
69,168

Related videos on Youtube

Aefits
Author by

Aefits

Updated on April 09, 2021

Comments

  • Aefits
    Aefits about 3 years

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

    Can someone help?

    • Tim Biegeleisen
      Tim Biegeleisen about 6 years
      Look into using SimpleDateFormat, or better yet try out the Java 8 date API.
  • s1m0nw1
    s1m0nw1 about 6 years
    should only be used if JDK <= 1.7 also note that the formatter is not threadsafe
  • Mihae Kheel
    Mihae Kheel about 3 years
    Note: This only work for SDK 26 and above for lower SDK follow this : developer.android.com/studio/write/…