Sling Academy
Home/Kotlin/Converting Epoch Time to Readable Date-Time in Kotlin

Converting Epoch Time to Readable Date-Time in Kotlin

Last updated: December 04, 2024

In software development, there often comes a time when you're dealing with epoch or UNIX time – a measurement of time that represents the number of seconds that have elapsed since January 1, 1970 (excluding leap seconds). Epoch time is used across different systems for a consistent method of tracking time. However, reading and understanding this numeric format isn't intuitive for humans, which is why converting epoch time to a more human-readable date-time format is necessary. In this article, we'll explore how to perform this conversion in Kotlin, a statically typed programming language that runs on the Java Virtual Machine and is a preferred language for Android development.

What is Epoch Time?

Epoch time, also known as Unix time, is a system for tracking time that counts the number of seconds since ‘the epoch’ (January 1, 1970, at midnight UTC). This method is useful in computing due to its simplicity, as it represents any date and time as a single number. However, for humans, this format isn't easily interpretable. Hence, converting epoch time to a more readable format like YYYY-MM-DD or the full date and time format is essential for user interfaces, reports, and logs.

Why Use Kotlin?

Kotlin is a modern language that enhances productivity and efficiency. It integrates seamlessly with Java and provides more concise and expressive syntax, which helps in writing cleaner and more comprehensible code. With first-class support from Google for Android development, Kotlin also offers robust functionality for handling dates and times, making it an excellent choice for this purpose.

Converting Epoch Time in Kotlin

To convert epoch time into a readable date and time format in Kotlin, the java.time package, available from Java 8 onwards, can be utilized. This offers a wide array of useful date and time classes.


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

fun epochToReadableDate(epochSeconds: Long): String {
    // Convert epoch time to an Instant
    val instant = Instant.ofEpochSecond(epochSeconds)
    
    // Convert the Instant to a LocalDateTime
    val dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
    
    // Define a formatter
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    
    // Format the LocalDateTime to a string
    return dateTime.format(formatter)
}

In this example, we first import necessary classes. The function epochToReadableDate takes in epoch seconds as a parameter. Using the Instant class, we convert these seconds to an instant, then convert the instant to a LocalDateTime object with the system's default time zone. Finally, we format this date and time using a specified pattern to make it easily readable.

Handling Time Zones

Time zones can be a tricky concept, as they vary in different regions of the world and affect date-time rendering. Therefore, it might be crucial to consider the time zone during conversion. By changing the ZoneId.systemDefault() in the above code to any desired time zone (like ZoneId.of("America/New_York")), you can get the corresponding local date and time.


fun epochToReadableDateWithTimeZone(epochSeconds: Long, timeZone: String): String {
    val instant = Instant.ofEpochSecond(epochSeconds)
    val dateTime = LocalDateTime.ofInstant(instant, ZoneId.of(timeZone))
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    return dateTime.format(formatter)
}

In the updated function above, you should pass the desired time zone along with the epoch seconds, and you can convert it to the locale’s date-time format accordingly.

Conclusion

Converting epoch time to a human-readable date-time format is straightforward with Kotlin's robust libraries. By leveraging the java.time package, you can handle these conversions efficiently and seamlessly within the Kotlin ecosystem. This integration and ease of use make Kotlin an excellent choice for handling date-time operations robustly while writing clean and maintainable code.

Next Article: How to Use Kotlin Coroutines for Scheduling Time-Based Tasks

Previous Article: Using Kotlin to Format Dates for Internationalization

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