Sling Academy
Home/Kotlin/Converting a Timestamp into a Readable Format in Kotlin

Converting a Timestamp into a Readable Format in Kotlin

Last updated: December 04, 2024

When developing applications in Kotlin, you often encounter timestamps, which represent the number of milliseconds since the Unix epoch (1st January 1970, 00:00:00 UTC). While extremely useful, timestamps aren't exactly human-friendly. To improve user experience, converting these timestamps into a more readable date and time format is a common requirement. This article will guide you through various methods to achieve this using the Kotlin programming language.

Using SimpleDateFormat

The SimpleDateFormat class from Java's java.text package provides a straightforward way to convert a timestamp into a readable format. Here's how you can use it in Kotlin:


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

fun convertTimestampToReadableFormat(timestamp: Long): String {
    val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    val date = Date(timestamp)
    return sdf.format(date)
}

fun main() {
    val timestamp = System.currentTimeMillis()
    println("Readable Date: " + convertTimestampToReadableFormat(timestamp))
}

In this snippet, we utilize the SimpleDateFormat to define our desired date format. The format "yyyy-MM-dd HH:mm:ss" corresponds to a readable String of full year, month, day, hour, minute, and seconds.

Using DateTimeFormatter (Java Time)

Since Java 8, the java.time package offers another, arguably more modern approach to date and time handling with the DateTimeFormatter. Kotlin is fully interoperable with this package. Here's how:


import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter

fun convertWithDateTimeFormatter(timestamp: Long): String {
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        .withZone(ZoneId.systemDefault())
    val dateTime = Instant.ofEpochMilli(timestamp)
    return formatter.format(dateTime)
}

fun main() {
    val timestamp = System.currentTimeMillis()
    println("Formatted with DateTimeFormatter: " + convertWithDateTimeFormatter(timestamp))
}

This approach leverages the DateTimeFormatter, providing increased functionality and flexibility over SimpleDateFormat. The withZone(ZoneId.systemDefault()) line ensures that the output is adjusted according to the system's default time zone.

Converting Timestamp to LocalDate

Another useful format is LocalDate when you only need the date part without any time of day considerations. Here’s how you could implement it:


import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId

fun convertToLocalDate(timestamp: Long): LocalDate {
    return Instant.ofEpochMilli(timestamp)
        .atZone(ZoneId.systemDefault())
        .toLocalDate()
}

fun main() {
    val timestamp = System.currentTimeMillis()
    println("Local Date: ${convertToLocalDate(timestamp)}")
}

This function makes use of Instant and ZoneId to derive a LocalDate instance that corresponds to the provided timestamp, conveniently ignoring any specific time information.

Conclusion

Converting timestamps into a readable format in Kotlin can be efficiently managed through several methods. Whether employing SimpleDateFormat for quick and easy formatting, using DateTimeFormatter from the java.time package for precision and modernization, or simply extracting a LocalDate, Kotlin provides multiple highly effective approaches for handling date and time. Choosing the method depends on the specific needs and context of your application.

Next Article: Generating Timestamps for Logging in Kotlin

Previous Article: How to Calculate Elapsed Time in Kotlin

Series: Working with date & time in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin