37

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

Can someone help?

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Aefits
  • 3,399
  • 6
  • 28
  • 46

3 Answers3

64

use this to convert the date string to UNIX timestamp

val date = SimpleDateFormat("dd-MM-yyyy").parse("14-02-2018")
println(date.time)
Arpan Sarkar
  • 2,301
  • 2
  • 13
  • 24
30

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.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • 5
    Note: This only work for SDK 26 and above for lower SDK follow this : https://developer.android.com/studio/write/java8-support#library-desugaring – Mihae Kheel Apr 09 '21 at 05:54
5

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")
Mihae Kheel
  • 2,441
  • 3
  • 14
  • 38