Search documentation of Localize

# Localize.DateTime.Relative (Localize v0.39.0)

Copy Markdown View Source

Formats relative time strings such as "3 days ago", "tomorrow", or "in 10 seconds".

Supports integer offsets (in seconds), `Date`, `DateTime`, `NaiveDateTime`, and `Time` structs.

## Summary

### Functions

known_units()

Returns the list of known time units.

to_string(relative, options \\ [])

Returns a string representing a relative time for a given number, date, time, or datetime.

to_string!(relative, options \\ [])

Same as `to_string/2` but raises on error.

## Functions

# known_units()

    @spec known_units() :: [atom(), ...]

Returns the list of known time units.

# to_string(relative, options \\ [])

    @spec to_string(integer() | Date.t() | DateTime.t() | Time.t(), Keyword.t()) ::
      {:ok, String.t()} | {:error, Exception.t()}

Returns a string representing a relative time for a given number, date, time, or datetime.

### Arguments

- `relative` is an integer (seconds from now), or a `Date`, `DateTime`, `NaiveDateTime`, or `Time` struct.

- `options` is a keyword list of options.

### Options

- `:locale` is a locale identifier. The default is `:en`.

- `:format` is `:standard`, `:narrow`, or `:short`. The default is `:standard`.

- `:unit` is the time unit for formatting. One of `:second`, `:minute`, `:hour`, `:day`, `:week`, `:month`, `:year`, `:mon`, `:tue`, `:wed`, `:thu`, `:fri`, `:sat`, `:sun`, `:quarter`. If omitted, a unit is derived automatically.

- `:relative_to` is the baseline date/datetime from which the difference is calculated. Defaults to now.

### Returns

- `{:ok, formatted_string}` on success.

- `{:error, exception}` on failure.

### Examples

    iex> Localize.DateTime.Relative.to_string(-1, unit: :day, locale: :en)
    {:ok, "yesterday"}

    iex> Localize.DateTime.Relative.to_string(1, unit: :day, locale: :en)
    {:ok, "tomorrow"}

    iex> Localize.DateTime.Relative.to_string(-3, unit: :day, locale: :en)
    {:ok, "3 days ago"}

    iex> Localize.DateTime.Relative.to_string(2, unit: :hour, locale: :en)
    {:ok, "in 2 hours"}

# to_string!(relative, options \\ [])

    @spec to_string!(integer() | Date.t() | DateTime.t() | Time.t(), Keyword.t()) ::
      String.t()

Same as `to_string/2` but raises on error.