Convert a String to Date in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.time.LocalDate import java.time.format.DateTimeFormatter fun main() { val dateString = "1 January, 2018" val formatter = DateTimeFormatter.ofPattern("d MMMM, yyyy") val date = LocalDate.parse(dateString, formatter) println(date) // 2018-01-01 } |
Alternately, you can use java.time.LocalDateTime to parse a string representing both date and time.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.time.LocalDateTime import java.time.format.DateTimeFormatter fun main() { val dateString = "Jan 01 2017, 07:34:27 pm" val formatter = DateTimeFormatter.ofPattern("MMM dd yyyy, hh:mm:ss a") val date = LocalDateTime.parse(dateString, formatter) println(date) // 2017-01-01T19:34:27 } |
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:
|
1 2 3 4 5 6 7 8 9 10 |
import java.time.Instant import java.time.ZoneId fun main() { val dateString = "2017-10-15T05:30:00Z" val timestamp = Instant.parse(dateString) println(timestamp) println(timestamp.atZone(ZoneId.of("Australia/Sydney"))) } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
import java.text.SimpleDateFormat fun main() { val dateString = "01.01.2017" val formatter = SimpleDateFormat("MM.dd.yyyy") val date = formatter.parse(dateString) println(date) // Sun Jan 01 00:00:00 IST 2017 } |
That’s all about converting String to Date in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)