English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to convert a string to a date

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to use formatters to convert strings to dates in Kotlin.

Example1:Use the predefined formatter to convert a string to a date

import java.time.LocalDate
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
    // Format y-M-d or yyyy-MM-d
    val string = ""2017-07-25"
    val date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE)
    println(date)
}

When the program is run, the output is:

2017-07-25

In the above program, we used the predefined formatter ISO DATE, which takes the format2017-07-25or2017-07-25+05:45the date string in '
The parse() function of LocalDate uses the given formatter to parse the given string. You can also remove the ISO date formatter in the above example and replace the parse() method with

LocalDate date = LocalDate.parse(string, DateTimeFormatter);

Example2:Use the pattern formatter to convert a string to a date

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
fun main(args: Array<String>) {
    val string = "July" 25, 2017"
    val formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH)
    val date = LocalDate.parse(string, formatter)
    println(date)
}

When the program is run, the output is:

2017-07-25

In the above program, our date format is MMMM d, yyyy. Therefore, we created the formatter with the given pattern.

Now, we can use the LocalDate.parse() function to parse the date and get the LocalDate object.

Here is the equivalent Java code:Java Program to Convert String to Date

Comprehensive Collection of Kotlin Examples