Calculating the Difference Between Two Time Periods in Scala
Scala is a powerful hybrid language that blends object-oriented and functional programming paradigms. It runs on the JVM, making it compatible with Java libraries—including those used for date and time manipulation.
For time-based operations, Scala developers often use Java’s LocalDateTime
and Duration
classes from the java.time
package.
In this sub-article, we’ll create a Scala program to compute the difference between two time points.
This follows the logic from our lead C article but applies idiomatic Scala code using modern libraries.
Scala Program: Calculate the Difference Between Two Time Periods
// DIFFERENCE BETWEEN TWO TIME PERIODS in Scala using java.time
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.Duration
object W3CW extends App {
// Step-1 Define formatter and input time strings
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val startTime = LocalDateTime.parse("2026-02-01 06:30:00", formatter)
val endTime = LocalDateTime.parse("2026-02-09 13:05:45", formatter)
// Step-2 Calculate duration
val duration = Duration.between(startTime, endTime)
val totalSeconds = duration.getSeconds
// Step-3 Extract hours, minutes, and seconds
val hours = totalSeconds / 3600
val minutes = (totalSeconds % 3600) / 60
val seconds = totalSeconds % 60
// Step-4 Display the result
println(s"\nTIME DIFFERENCE: $hours HOURS, $minutes MINUTES, $seconds SECONDS")
}
Output
TIME DIFFERENCE: 199 HOURS, 35 MINUTES, 45 SECONDS
Explanation
-
LocalDateTime.parse()
is used with a formatter to read string-based date-time. -
Duration.between()
computes the time difference. -
The result is formatted into hours, minutes, and seconds.
This solution is particularly useful in back-end services, analytics pipelines, or data transformation tasks written in Scala.
Extra Metric: Time Difference in Milliseconds
For high-precision use cases like log tracing or performance benchmarking, you can get the time difference in milliseconds:
val millis = duration.toMillis
println(s"TOTAL DURATION IN MILLISECONDS: $millis")
Output
OTAL DURATION IN MILLISECONDS: 718545000
This is helpful for applications that require fine-grained time analysis or timing-based validations.