Sling Academy
Home/Kotlin/How to convert date time to time ago in Kotlin

How to convert date time to time ago in Kotlin

Last updated: December 04, 2024

When developing applications, you often need to display the time in a format that is user-friendly and easy to understand. Instead of showing the exact date and time, many applications show a 'time ago' format. In this article, we'll explore how to convert date and time to a 'time ago' format in Kotlin, a modern, statically-typed programming language that was designed as an improvement to Java.

Understanding the Task

Converting a date-time to a 'time ago' format takes a timestamp or a date-time object and calculates the elapsed time from that moment to now, expressing it in terms like "2 seconds ago", "3 minutes ago," "5 days ago," and so on.

Setting Up Your Kotlin Project

Before we begin coding, make sure you have a Kotlin project set up. You can use an IDE like IntelliJ IDEA or a simple text editor along with command line tools. Ensure you have the Kotlin SDK installed on your system. If not, you can download it from Kotlin's official website.

Converting Date and Time to 'Time Ago' in Kotlin

We'll create a function in Kotlin that takes a java.util.Date object and returns a string representing the 'time ago' format.

Basic Implementation

Let's write a Kotlin function that calculates and formats the elapsed time from a date to now:


import java.util.Date

fun getTimeAgo(date: Date): String {
    val now = Date().time
    val timePassed = now - date.time

    val seconds = timePassed / 1000
    val minutes = seconds / 60
    val hours = minutes / 60
    val days = hours / 24

    return when {
        seconds < 60 -> "$seconds seconds ago"
        minutes < 60 -> "$minutes minutes ago"
        hours < 24 -> "$hours hours ago"
        else -> "$days days ago"
    }
}

In this example, we calculate the time difference between the current time and the given date in milliseconds. We convert the milliseconds to seconds, minutes, hours, and days, then use a simple conditional statement to create a readable string.

Handling Plurals

To handle plural forms correctly ("1 second ago" vs "2 seconds ago"), we can enhance the function like this:


fun getTimeAgo(date: Date): String {
    val now = Date().time
    val timePassed = now - date.time

    val seconds = timePassed / 1000
    val minutes = seconds / 60
    val hours = minutes / 60
    val days = hours / 24

    return when {
        seconds < 60 -> "${seconds} ${if (seconds == 1L) "second" else "seconds"} ago"
        minutes < 60 -> "${minutes} ${if (minutes == 1L) "minute" else "minutes"} ago"
        hours < 24 -> "${hours} ${if (hours == 1L) "hour" else "hours"} ago"
        else -> "${days} ${if (days == 1L) "day" else "days"} ago"
    }
}

This implementation includes a proper singular and plural handling for different time intervals.

Using Kotlin Extensions

Kotlin is known for its extension functions, which allow you to add functionality to existing classes. Below is a version using an extension function on the Date class:


import java.util.Date

fun Date.toTimeAgo(): String {
    val now = Date().time
    val timePassed = now - this.time

    val seconds = timePassed / 1000
    val minutes = seconds / 60
    val hours = minutes / 60
    val days = hours / 24

    return when {
        seconds < 60 -> "${seconds} ${if (seconds == 1L) "second" else "seconds"} ago"
        minutes < 60 -> "${minutes} ${if (minutes == 1L) "minute" else "minutes"} ago"
        hours < 24 -> "${hours} ${if (hours == 1L) "hour" else "hours"} ago"
        else -> "${days} ${if (days == 1L) "day" else "days"} ago"
    }
}

By adding toTimeAgo as an extension function, you can call it directly on any Date object.

Conclusion

In this article, we learnt how to convert a timestamp to a user-friendly 'time ago' format using Kotlin. We've covered a straightforward approach that you can further develop to meet the specific needs of your application. Also, take advantage of Kotlin's features like extension functions to keep your code clean and concise. As you continue using Kotlin, you'll discover many more ways to make your coding life easier and more productive.

Previous Article: Best Practices for Date-Time Calculations in Kotlin Applications

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