Sling Academy
Home/Kotlin/How to Truncate Time to Remove Seconds or Milliseconds in Kotlin

How to Truncate Time to Remove Seconds or Milliseconds in Kotlin

Last updated: December 04, 2024

Truncating time involves reducing the level of detail in a time or date object. For instance, you might want to truncate a timestamp such that it removes the seconds or milliseconds component, leaving only the more significant elements like hours and minutes. In this tutorial, we will learn how to achieve this truncation in Kotlin by using various techniques and libraries.

Using Java's LocalDateTime and ChronoUnit

Kotlin runs on the Java Virtual Machine (JVM) and therefore has access to all of Java's great tools and libraries including LocalDateTime from java.time package. We can leverage ChronoUnit to easily truncate what we need.


import java.time.LocalDateTime
import java.time.temporal.ChronoUnit

fun truncateTimeToMinutes(dateTime: LocalDateTime): LocalDateTime {
    return dateTime.truncatedTo(ChronoUnit.MINUTES)
}

fun main() {
    val current = LocalDateTime.now()
    println("Current DateTime: $current")
    val truncated = truncateTimeToMinutes(current)
    println("Truncated DateTime: $truncated")
}

Here, truncatedTo(ChronoUnit.MINUTES) allows us to remove the seconds and milliseconds, effectively rounding down to the nearest minute.

Using third-party libraries like ThreeTenABP for Android

If you are working on an Android project that targets older versions and the java-time API is not fully supported, consider using the ThreeTenABP library, a backport of Java's time library. Assuming the library is correctly added to your project:


import org.threeten.bp.LocalDateTime
import org.threeten.bp.temporal.ChronoUnit

fun truncateTime(dateTime: LocalDateTime): LocalDateTime {
    return dateTime.truncatedTo(ChronoUnit.MINUTES)
}

fun main() {
    val currentDateTime = LocalDateTime.now()
    println("Current: $currentDateTime")
    val truncatedDateTime = truncateTime(currentDateTime)
    println("Truncated: $truncatedDateTime")
}

The truncatedTo function in this snippet works similarly to the JVM version, simplifying the process of eliminating unwanted time granularity in the data we process.

Custom Format Parsing and Truncating

In some cases, you may not want to rely on the standard libraries for truncation. Creating a custom truncation function can provide additional flexibility. Here, we use Java's SimpleDateFormat to control the pattern for date and time parsing.


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

fun truncateUsingFormat(date: Date): Date {
    val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm")
    val formattedDate = dateFormatter.format(date)
    return dateFormatter.parse(formattedDate) ?: date
}

fun main() {
    val current = Date()
    println("Current Date: ${current}")
    val truncated = truncateUsingFormat(current)
    println("Truncated Date: ${truncated}")
}

With SimpleDateFormat, we specify only the desired time components. Note, however, that this approach converts your Date objects to and from String, which could introduce performance drawbacks compared to other methods.

Conclusion

Kotlin offers several options for truncating time down to minutes, removing seconds or milliseconds from your date and time data. Whether you're leveraging Java's existing libraries or employing third-party libraries for Android development, there's a technique that fits the requirements of your project. Select based on efficiency, simplicity, or compatibility with the platforms your app is targeting.

Next Article: Combining Date and Time into a Single Object in Kotlin

Previous Article: Finding the Start and End of a Day 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