I want to convert a date string to unix timestamp from a date string e.g. 14-02-2018
Can someone help?
Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.
The default way of formatting Date using default format in Kotlin is invoking the toString() method. This looks readable as the output format is yyyy-MM-dd, but again, we may need to format the date to custom formats depending on our use-cases.
use this to convert the date string to UNIX timestamp
val date = SimpleDateFormat("dd-MM-yyyy").parse("14-02-2018") println(date.time)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With