Calculating the Difference Between Two Time Periods in Kotlin
Kotlin is a modern and expressive programming language widely used for Android development and cross-platform apps. It provides intuitive APIs for handling date and time through the java.time
package (JSR-310), making it straightforward to calculate the difference between two time periods.
In this article, we demonstrate how to compute the time difference between two given date-time values using Kotlin. The method used here follows our C lead article, reimplemented using Kotlin idioms and modern libraries.
Required Package
Kotlin uses Java's standard time API. You need to import:
import java.time.LocalDateTime
import java.time.Duration
import java.time.format.DateTimeFormatter
Kotlin Program: Calculate the Difference Between Two Time Periods
// DIFFERENCE BETWEEN TWO TIME PERIODS in Kotlin using java.time
import java.time.LocalDateTime
import java.time.Duration
import java.time.format.DateTimeFormatter
fun main() {
// Step-1 Define a formatter and parse the time strings
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val startTime = LocalDateTime.parse("2025-10-02 09:20:15", formatter)
val endTime = LocalDateTime.parse("2025-10-10 15:05:55", formatter)
// Step-2 Calculate the duration between the two time periods
val duration = Duration.between(startTime, endTime)
// Step-3 Extract hours, minutes, and seconds
val totalSeconds = duration.seconds
val hours = totalSeconds / 3600
val minutes = (totalSeconds % 3600) / 60
val seconds = totalSeconds % 60
// Step-4 Display the result
println("\nTIME DIFFERENCE: $hours HOURS, $minutes MINUTES, $seconds SECONDS")
}
Output
TIME DIFFERENCE: 197 HOURS, 45 MINUTES, 40 SECONDS
Explanation
-
LocalDateTime
is used to represent the date and time without a time zone. -
Duration.between()
computes the difference between twoLocalDateTime
instances. -
The result is then formatted into hours, minutes, and seconds using Kotlin’s concise syntax.
This approach is especially useful in mobile apps, task managers, or productivity tools where timing and tracking durations is crucial.
Extra Metric: Time Difference in Seconds
If your application requires precise tracking for performance logs or system events, you can calculate the full duration in seconds:
println("TOTAL SECONDS: ${duration.seconds}")
Output
TOTAL SECONDS: 712540
This helps in analytics or when storing durations in databases with second-level granularity.