Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 231
elegant-user Avatar asked Feb 17 '18 07:02

elegant-user


People also ask

How do I convert a string to a date?

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.

How do I change the date format in Kotlin?

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.


2 Answers

use this to convert the date string to UNIX timestamp

val date = SimpleDateFormat("dd-MM-yyyy").parse("14-02-2018") println(date.time) 
like image 122
Arpan Sarkar Avatar answered Sep 21 '22 17:09

Arpan Sarkar


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.

like image 34
s1m0nw1 Avatar answered Sep 20 '22 17:09

s1m0nw1