gleam/time/duration

Types

An amount of time, with up to nanosecond precision.

This type does not represent calendar periods such as “1 month” or “2 days”. Those periods will be different lengths of time depending on which month or day they apply to. For example, January is longer than February. A different type should be used for calendar periods.

pub opaque type Duration

Functions

pub fn add(left: Duration, right: Duration) -> Duration

Add two durations together.

Examples

add(seconds(1), seconds(5))
// -> seconds(6)
pub fn compare(left: Duration, right: Duration) -> Order

Compare one duration to another, indicating whether the first spans a larger amount of time (and so is greater) or smaller amount of time (and so is lesser) than the second.

Examples

compare(seconds(1), seconds(2))
// -> order.Lt

Whether a duration is negative or positive doesn’t matter for comparing them, only the amount of time spanned matters.

compare(seconds(-2), seconds(1))
// -> order.Gt
pub fn difference(left: Duration, right: Duration) -> Duration

Calculate the difference between two durations.

This is effectively substracting the first duration from the second.

Examples

difference(seconds(1), seconds(5))
// -> seconds(4)
pub fn milliseconds(amount: Int) -> Duration

Create a duration of a number of milliseconds.

pub fn nanoseconds(amount: Int) -> Duration

Create a duration of a number of nanoseconds.

JavaScript int limitations

Remember that JavaScript can only perfectly represent ints between positive and negative 9,007,199,254,740,991! If you use a single call to this function to create durations larger than that number of nanoseconds then you will likely not get exactly the value you expect. Use seconds and milliseconds as much as possible for large durations.

pub fn seconds(amount: Int) -> Duration

Create a duration of a number of seconds.

pub fn to_iso8601_string(duration: Duration) -> String

Convert the duration to an ISO8601 formatted duration string.

The ISO8601 duration format is ambiguous without context due to months and years having different lengths, and because of leap seconds. This function encodes the duration as days, hours, and seconds without any leap seconds. Be sure to take this into account when using the duration strings.

pub fn to_seconds(duration: Duration) -> Float

Convert the duration to a number of seconds.

There may be some small loss of precision due to Duration being nanosecond accurate and Float not being able to represent this.

pub fn to_seconds_and_nanoseconds(
  duration: Duration,
) -> #(Int, Int)

Convert the duration to a number of seconds and nanoseconds. There is no loss of precision with this conversion on any target.

Search Document