This post will discuss how to convert a string to a Date in Kotlin.

1. Using LocalDate.parse() function

The recommended solution is to use DateTimeFormatter to create a formatter object and pass it to the LocalDate.parse() function with the date string. The java.time.LocalDate is the standard class for representing a date without a time.

Download Code

 
Alternately, you can use java.time.LocalDateTime to parse a string representing both date and time.

Download Code

2. Using Instant.parse() function

If your string represents a valid instant in UTC, you can use the Instant.parse() function to get an java.time.Instant instance. Note that the string is parsed internally using DateTimeFormatter.ISO_INSTANT and can be parsed with a specific time zone:

Download Code

Output:

2017-10-15T05:30:00Z
2017-10-15T11:00+05:30[Asia/Kolkata]

3. Using SimpleDateFormat class

Another solution is to use the java.util.SimpleDateFormat class to format and parse dates in Kotlin, which allows you to define your date and time pattern strings for date-time formatting using the standard pattern letters.

Download Code

That’s all about converting String to Date in Kotlin.