Intl.DurationFormat (Intl v0.2.0)

Copy Markdown View Source

Locale-sensitive duration formatting, modelled on Intl.DurationFormat.

Formats durations as human-readable strings such as "11 months and 30 days" or "2 hours, 30 minutes, and 45 seconds".

Delegates to Localize.Duration for the underlying formatting.

Accepts either a Localize.Duration struct or a plain map with duration component keys (matching the JS DurationFormat input shape).

Summary

Functions

Formats a duration according to locale conventions.

Formats a duration, raising on error.

Functions

format(duration_or_map, options \\ [])

@spec format(Localize.Duration.t() | map(), Keyword.t()) ::
  {:ok, String.t()} | {:error, term()}

Formats a duration according to locale conventions.

Arguments

  • duration is a Localize.Duration struct or a map with any of the keys :years, :months, :days, :hours, :minutes, :seconds (plural, matching the JS API), or the singular Elixir equivalents :year, :month, :day, :hour, :minute, :second.

  • options is a keyword list of options.

Options

  • :locale is a locale identifier string or atom. The default is the current process locale.

  • :style is :long, :short, or :narrow. The default is :long.

Returns

  • {:ok, formatted_string} on success.

  • {:error, reason} if the duration or options are invalid.

Examples

iex> {:ok, d} = Localize.Duration.new(~D[2019-01-01], ~D[2019-12-31])
iex> Intl.DurationFormat.format(d, locale: :en)
{:ok, "11 months and 30 days"}

iex> Intl.DurationFormat.format(%{hours: 2, minutes: 30}, locale: :en)
{:ok, "2 hours and 30 minutes"}

format!(duration, options \\ [])

@spec format!(Localize.Duration.t() | map(), Keyword.t()) :: String.t() | no_return()

Formats a duration, raising on error.

Same as format/2 but returns the string directly or raises.

Arguments

  • duration is a Localize.Duration struct or a map.

  • options is a keyword list of options.

Returns

  • A formatted string.

Examples

iex> Intl.DurationFormat.format!(%{hours: 2, minutes: 30}, locale: :en)
"2 hours and 30 minutes"