1. Overview

Duration and FiniteDuration both represent a time frame. Duration is an abstract class, and FiniteDuration is a final implementation of Duration. In this article, we’ll demonstrate use cases, transformations, and utility functions for these classes.

2. Initialization, Operators, and Comparisons

2.1. Initialization

We can instantiate a Duration object in many ways:

val duration1 = Duration("5 seconds")
val duration2 = Duration(5, TimeUnit.SECONDS)
val duration3 = 5.seconds
val duration4 = 250.millis

2.2. Operators

Duration supports the +, , and * operators:

val addition = Duration("5 seconds") + Duration(5, TimeUnit.SECONDS) // 10 seconds
val subtraction = 5.seconds - 5.seconds // 0 seconds
val product = 5.seconds * 3 // 15 seconds

We can also use division, which has two variants:

val division1 = 5.seconds / 2 // 2500 milliseconds
val division2 = 5.seconds / Duration("5 seconds") // 1.0

A duration divided by a number results in a new duration that is essentially the dividend divided by the given number. On the other hand, a duration divided by a duration results in a number that describes how many times the divisor should be multiplied to result in the dividend.

2.3. Comparisons

Comparisons are also supported via the operators <, <=, >, and >=:

val result1 = 5.seconds < 1000.millis // false
val result2 = 5.seconds <= 1000.millis // false
val result3 = 5.seconds > 1000.millis // true
val result4 = 5.seconds >= 1000.millis // true

Another way to compare two given duration objects is the compare() function:

val result5 = 5.seconds.compare(1000.millis) // 1

The compare() function returns a positive number if the compared Duration is greater than the argument, negative if the compared Duration is less than the argument, and zero if the two Durations are equal.

3. Conversions and Utilities

3.1. TimeUnit Conversions

We can extract a Duration‘s time unit with the related helper functions:

20.days.toMillis // 1728000000L
20.days.toSeconds // 1728000L
20.days.toHours // 480L
20.days.toMinutes // 28800L

3.2. Deadline Conversion

The Deadline describes a time-based countdown. Function fromNow converts a Duration into a Deadline:

val deadline = 100.millis.fromNow // Deadline(1302934436354298 nanoseconds)
val hasTimeLeft = deadline.hasTimeLeft() // true
val isOverdue = deadline.isOverdue() // false
Thread.sleep(100L) // sleeping for the duration of the deadline
val hasTimeLeft2 = deadline.hasTimeLeft() // false
val isOverdue2 = deadline.isOverdue() // true

3.3. Coarsest

Function toCoarsest returns the Duration to the coarsest unit possible:

5000.millis.toCoarsest // 5 seconds
5.seconds.toCoarsest // 5 seconds

4. Conclusion

In this article, we presented basic usage, transformations, and utility functions for the Duration and FiniteDuration classes.

Comments are closed on this article!