calendar/duration

Types

Struct and functions for handling durations.

A Duration struct represents a collection of time scale units, allowing for manipulation and calculation of durations.

Date and time scale units are represented as integers, allowing for both positive and negative values.

Microseconds are represented using a tuple #(microsecond, precision). This ensures compatibility with other calendar types implementing time, such as Time, DateTime, and NaiveDateTime.

pub type Duration {
  Duration(
    year: Int,
    month: Int,
    week: Int,
    day: Int,
    hour: Int,
    minute: Int,
    second: Int,
    microsecond: #(Int, Int),
  )
}

Constructors

  • Duration(
      year: Int,
      month: Int,
      week: Int,
      day: Int,
      hour: Int,
      minute: Int,
      second: Int,
      microsecond: #(Int, Int),
    )
pub type ParseError {
  InvalidFormat
  InvalidDuration
}

Constructors

  • InvalidFormat
  • InvalidDuration
pub type UnitPair {
  Year(Int)
  Month(Int)
  Week(Int)
  Day(Int)
  Hour(Int)
  Minute(Int)
  Second(Int)
  Microsecond(#(Int, Int))
}

Constructors

  • Year(Int)
  • Month(Int)
  • Week(Int)
  • Day(Int)
  • Hour(Int)
  • Minute(Int)
  • Second(Int)
  • Microsecond(#(Int, Int))

Values

pub fn add(d1: Duration, d2: Duration) -> Duration

Adds two durations together.

pub fn from_iso8601(
  duration_string: String,
) -> Result(Duration, ParseError)

Parses an ISO8601 duration string.

Examples:

  • “P1Y2M3DT4H5M6S” -> 1 year, 2 months, 3 days, 4 hours, 5 minutes, 6 seconds
  • “P1W” -> 1 week
  • “PT30M” -> 30 minutes
pub fn from_iso8601_unchecked(
  duration_string: String,
) -> Duration

Parses an ISO8601 duration string, panicking on invalid input.

pub fn from_unit_pairs(pairs: List(UnitPair)) -> Duration

Creates a new Duration from a list of unit pairs.

pub fn multiply(duration: Duration, multiplier: Int) -> Duration

Multiplies a duration by an integer.

pub fn negate(duration: Duration) -> Duration

Negates a duration (makes positive units negative and vice versa).

pub fn new() -> Duration

Creates a new Duration struct with all units set to zero.

pub fn subtract(d1: Duration, d2: Duration) -> Duration

Subtracts the second duration from the first.

pub fn to_iso8601(duration: Duration) -> String

Converts a duration to ISO8601 format.

pub fn to_string(duration: Duration) -> String

Converts a duration to a human-readable string.

pub fn to_timeout(duration: Duration) -> Int

Converts a duration to a timeout value in milliseconds. Raises if the duration contains non-zero year or month values, as those cannot be reliably converted.

Search Document