PureAdmin.DateTime (PureAdmin v1.1.0)

Copy Markdown View Source

Date, time, and relative-time formatting with translation support.

Works with Date, Time, DateTime, and NaiveDateTime. Month names, weekday names, and relative phrases all flow through PureAdmin.Translations.t/2, so apps that configure a translation callback automatically get localized output without any code changes.

Quick use

alias PureAdmin.DateTime, as: PADT

PADT.format(~U[2026-04-23 16:29:22Z], :short_date)
# => "2026-04-23"

PADT.format(~U[2026-04-23 16:29:22Z], :long_date)
# => "April 23, 2026"

PADT.format(~U[2026-04-23 16:29:22Z], :short_date_time)
# => "2026-04-23 16:29"

PADT.format(~U[2026-04-23 16:29:22Z], :long_date_time)
# => "April 23, 2026 at 16:29"

PADT.format(~U[2026-04-23 16:29:22Z], :time)
# => "16:29"

PADT.relative(DateTime.add(DateTime.utc_now(), -300, :second))
# => "5 minutes ago"

Styles

StyleExample
:short_date2026-04-23
:long_dateApril 23, 2026
:full_dateThursday, April 23, 2026
:time16:29
:long_time16:29:22
:short_date_time2026-04-23 16:29
:long_date_timeApril 23, 2026 at 16:29
:relative5 minutes ago, in 2 hours

You can also pass a raw strftime pattern string — it's piped through Calendar.strftime/2 after month/weekday name substitution.

PADT.format(dt, "%B %d, %Y")

Relative time

relative/2 expresses how far datetime is from now:

  • ≤ 5 s → now
  • < 1 m → %{count}s ago
  • < 1 h → a minute ago, %{count} minutes ago
  • < 1 d → an hour ago, %{count} hours ago
  • < 2 d → yesterday
  • < 1 w → %{count} days ago
  • < 1 mo → a week ago, %{count} weeks ago
  • < 1 y → a month ago, %{count} months ago
  • older → a year ago, %{count} years ago

Future times use in %{duration} (e.g. in 3 hours).

Pass :now to stabilize tests:

PADT.relative(event_at, now: ~U[2026-04-23 16:29:22Z])

Translation keys

All keys sit under pureAdmin.datetime.*. See PureAdmin.Translations module doc for how to wire a callback. Month names live under pureAdmin.datetime.months.*, weekday names under pureAdmin.datetime.weekdays.*, and relative phrases directly under pureAdmin.datetime.* (e.g. pureAdmin.datetime.minutesAgo).

Summary

Functions

Formats datetime as style.

Formats datetime as a relative phrase (e.g. "5 minutes ago").

Types

formattable()

@type formattable() :: Date.t() | Time.t() | NaiveDateTime.t() | DateTime.t()

style()

@type style() ::
  :short_date
  | :long_date
  | :full_date
  | :time
  | :long_time
  | :short_date_time
  | :long_date_time
  | :relative
  | String.t()

Functions

format(datetime, style \\ :short_date_time)

@spec format(formattable(), style()) :: String.t()

Formats datetime as style.

See the module doc for the list of styles and examples.

relative(datetime, opts \\ [])

@spec relative(
  formattable(),
  keyword()
) :: String.t()

Formats datetime as a relative phrase (e.g. "5 minutes ago").

Accepts :now option to override the reference time (useful in tests).