Search documentation of Localize

# Localize.DateTime (Localize v0.39.0)

Copy Markdown View Source

Provides localized formatting of `DateTime`, `NaiveDateTime`, and datetime-like maps.

The primary function is `to_string/2` which accepts a datetime value and an options keyword list. Format patterns are defined in CLDR and described in TR35.

## Predefined formats

- `:short` — abbreviated date and time (e.g., "1/2/25, 3:04 PM").

- `:medium` — standard date and time (default).

- `:long` — includes time zone name.

- `:full` — verbose day-of-week, date, and time zone.

Custom CLDR skeleton strings and raw format patterns are also supported via the `:format` option.

## Summary

### Functions

to_string(datetime, options \\ [])

Formats a datetime according to a CLDR format pattern.

to_string!(datetime, options \\ [])

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

## Functions

# to_string(datetime, options \\ [])

    @spec to_string(map(), Keyword.t()) :: {:ok, String.t()} | {:error, Exception.t()}

Formats a datetime according to a CLDR format pattern.

### Arguments

- `datetime` is a `DateTime.t/0`, `NaiveDateTime.t/0`, or any map with date and time keys.

- `options` is a keyword list of options.

### Options

- `:format` is a standard format name (`:short`, `:medium`, `:long`, `:full`) or a format pattern string. The default is `:medium`.

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

- `:prefer` selects between CLDR `alt` variants. Accepts an atom or a list of atoms in priority order. Recognised values: `:standard` / `:variant` (locales like en-CA publish both an ISO pattern `"y-MM-dd"` and a locale-variant `"d/M/yy"`), and `:unicode` / `:ascii` (mostly time formats — NBSP and curly quotes vs ASCII-only). Examples: `prefer: :variant`, `prefer: [:variant, :ascii]`. The default is `[:standard, :unicode]`.

### Returns

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

- `{:error, exception}` if the datetime cannot be formatted.

### Examples

    iex> Localize.DateTime.to_string(~N[2017-07-10 14:30:00], locale: :en, prefer: :ascii)
    {:ok, "Jul 10, 2017, 2:30:00 PM"}

    iex> Localize.DateTime.to_string(~N[2017-07-10 14:30:00], format: :short, locale: :en, prefer: :ascii)
    {:ok, "7/10/17, 2:30 PM"}

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

    @spec to_string!(map(), Keyword.t()) :: String.t()

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