Back to Blog

Kotlin: Convert string to date

Sandy LaneSandy Lane

Video: Kotlin: Convert string to date by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: Convert String to Date

Converting a string to a date in Kotlin is a common task when working with date and time data from user input or external sources. Kotlin leverages Java's date-time APIs, such as SimpleDateFormat or the modern java.time package, to parse strings into date objects safely and efficiently.

Code

import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

fun main() {
  val dateString = "2024-06-15"
  // Define the date format matching the input string
  val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

  try {
    // Parse the string into a Date object
    val date: Date = format.parse(dateString)!!
    println("Parsed date: $date")
  } catch (e: Exception) {
    println("Error parsing date: ${e.message}")
  }
}

Key Points

  • Use SimpleDateFormat to define the expected date pattern for parsing strings.
  • Always handle parsing exceptions to avoid runtime crashes from invalid date formats.
  • The parsed Date object can then be used for date comparisons, formatting, or calculations.
  • For modern applications, consider using java.time.LocalDate and DateTimeFormatter for better API design and thread safety.