Duration
The Duration
data type data type is used to represent specific non-negative spans of time. It is commonly used to represent time intervals or durations in various operations, such as timeouts, delays, or scheduling. The Duration
type provides a convenient way to work with time units and perform calculations on durations.
The Duration module includes several constructors to create durations in different units.
Example (Creating Durations in Various Units)
You can create durations using units such as nanoseconds, microsecond, milliseconds, seconds, minutes, hours, days, and weeks.
For an infinite duration, use Duration.infinity
.
Example (Creating an Infinite Duration)
Another option for creating durations is using the Duration.decode
helper:
number
values are treated as milliseconds.bigint
values are treated as nanoseconds.- Strings must follow the format
"${number} ${unit}"
.
Example (Decoding Values into Durations)
You can retrieve the value of a duration in milliseconds using Duration.toMillis
.
Example (Getting Duration in Milliseconds)
To get the value of a duration in nanoseconds, use Duration.toNanos
. Note that toNanos
returns an Option<bigint>
because the duration might be infinite.
Example (Getting Duration in Nanoseconds)
To get a bigint
value without Option
, use Duration.unsafeToNanos
. However, it will throw an error for infinite durations.
Example (Retrieving Nanoseconds Unsafely)
Use the following functions to compare two durations:
API | Description |
---|---|
lessThan | Returns true if the first duration is less than the second. |
lessThanOrEqualTo | Returns true if the first duration is less than or equal to the second. |
greaterThan | Returns true if the first duration is greater than the second. |
greaterThanOrEqualTo | Returns true if the first duration is greater than or equal to the second. |
Example (Comparing Two Durations)
You can perform arithmetic operations on durations, like addition and multiplication.
Example (Adding and Multiplying Durations)