Converting a date into a string

Kotlin:
Converting a date into a string

How to:

In Kotlin, you can convert a Date to a String using the SimpleDateFormat class. Let’s roll some code:

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

fun main() {
    val date = Date() // Create a Date object for the current time
    val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // Define the date pattern
    val dateString = format.format(date) // Convert Date to String
    println(dateString) // Output the date string
}

Sample output might look like this:

2023-03-25 14:45:32

Deep Dive

Before java.time stepped onto the scene, SimpleDateFormat was the go-to guy for date-string transformations in Java and, by inheritance, in Kotlin. Yep, Kotlin runs on the Java Virtual Machine and interacts comfortably with Java libraries.

With Java 8, however, java.time entered the picture, bringing DateTimeFormatter with a much more refined API. This was a game-changer, offering safer, immutable, and thread-safe date-time manipulation. Kotlin’s native support for this is seamless:

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

fun main() {
    val currentDate = LocalDateTime.now() // Get current date and time
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    val formattedDate = currentDate.format(formatter)
    println(formattedDate)
}

Alternatives? Sure. For non-standard requirements or juggling between multiple date libraries, third-party options like Joda-Time used to be the golden standard. These days, java.time covers most bases.

As per implementation details, SimpleDateFormat isn’t thread-safe, which means it can trip over its laces when used in concurrent settings. DateTimeFormatter doesn’t have that issue. Create once, use forever—or at least throughout your application without fretting much.

See Also

  • DateTimeFormatter JavaDoc for all your pattern needs: DateTimeFormatter
  • If you’re feeling nostalgic or need examples for legacy systems, here’s the scoop on SimpleDateFormat: SimpleDateFormat