Sling Academy
Home/Kotlin/How to Round Time to the Nearest Minute or Hour in Kotlin

How to Round Time to the Nearest Minute or Hour in Kotlin

Last updated: December 04, 2024

Working with time data is a common requirement in software development, and Kotlin makes it straightforward to manipulate date and time values using its modern features. This article will illustrate how to round time to the nearest minute or hour in Kotlin using various programming strategies.

Understanding Kotlin's Time and Date Libraries

Kotlin does not natively handle date and time. Instead, it allows you to use Java's time handling libraries. With Kotlin, you can make use of Java's java.time package that offers a comprehensive set of classes to handle date and time manipulation simply and effectively. We will use LocalTime from this package to demonstrate rounding.

Rounding Down and Up

Before diving into rounding to the nearest time unit, it's essential to understand the concepts of rounding up and rounding down. Rounding down a time implies adjusting the time backwards to the last exact time unit increment. In contrast, rounding up adjusts the time forwards.

Rounding Time to the Nearest Minute

To round time to the nearest minute, you can leverage LocalTime for simplicity. Here's an example of how you can achieve this:


import java.time.LocalTime

fun roundToNearestMinute(time: LocalTime): LocalTime {
    val seconds = time.second
    val nanoAdjustment = time.nano
    return if (seconds >= 30 || (seconds == 29 && nanoAdjustment > 0)) {
        time.plusSeconds((60 - seconds).toLong()).withNano(0)
    } else {
        time.withSecond(0).withNano(0)
    }
}

fun main() {
    val time = LocalTime.of(13, 47, 45) // Lets say 13:47:45
    val rounded = roundToNearestMinute(time)
    println("Rounded Time: $rounded")
}

In this example, the function rounds 13:47:45 to 13:48 since 45 seconds is closer to the next minute.

Rounding Time to the Nearest Hour

Rounding time to the nearest whole hour follows a similar logic but focuses on the minutes instead:


fun roundToNearestHour(time: LocalTime): LocalTime {
    val minutes = time.minute
    return if (minutes >= 30) {
        time.plusHours(1).withMinute(0).withSecond(0).withNano(0)
    } else {
        time.withMinute(0).withSecond(0).withNano(0)
    }
}

fun main() {
    val time = LocalTime.of(13, 47) // Lets say 13:47
    val rounded = roundToNearestHour(time)
    println("Rounded Time: $rounded")
}

Here, 13:47 rounds up to 14:00 as 47 minutes is closer to the next full hour.

Using Extension Functions

Kotlin allows you to make use of extension functions to neatly organize your code when adding functionalities like time rounding. You could employ extension functions for conciseness as shown below:


import java.time.LocalTime

fun LocalTime.roundToMinute() = this.run { 
    if (this.second >= 30 || (this.second == 29 && this.nano > 0)) {
        this.plusSeconds((60 - this.second).toLong()).withNano(0)
    } else {
        this.withSecond(0).withNano(0)
    }
}

fun LocalTime.roundToHour() = this.run { 
    if (this.minute >= 30) {
        this.plusHours(1).withMinute(0).withSecond(0).withNano(0)
    } else {
        this.withMinute(0).withSecond(0).withNano(0)
    }
}

fun main() {
    val time = LocalTime.of(13, 47, 45)
    println("Rounded to nearest minute: ${time.roundToMinute()}")
    println("Rounded to nearest hour: ${time.roundToHour()}")
}

Using extension functions allows for elegant and readable code that smoothly extends existing classes with new behavior.

Conclusion

In this article, we explored how to round time to the nearest minute or hour in Kotlin, utilizing the java.time.LocalTime class. We reviewed basic examples using functions, as well as advanced usage with extension functions. Kotlin, through Java interoperability, offers robust capabilities for dealing with time manipulations, and rounding time is a fundamental aspect that's easily implemented using these approaches.

Next Article: Using `Clock` for Mocking Time in Kotlin Tests

Previous Article: Parsing Multiple Date Formats 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