defmodule FastLocalDatetime do @moduledoc """ Fast conversions of UTC epoch timestamps (Unix timestamps) into a local DateTime. """ alias FastLocalDatetime.{Table, TableRegistry, TableSupervisor} @doc """ Convert a UTC epoch timestamp (Unix timestamp) to a DateTime in the given timezone. iex> {:ok, dt} = unix_to_datetime(1522888537, "America/New_York") iex> dt #DateTime<2018-04-04 20:35:37-04:00 EDT America/New_York> iex> unix_to_datetime(1522888537, "not found") {:error, :not_found} """ @spec unix_to_datetime(timestamp, timezone) :: {:ok, DateTime.t()} | {:error, :not_found} when timestamp: integer, timezone: String.t() def unix_to_datetime(unix, timezone) when is_integer(unix) and is_binary(timezone) do with {:ok, table} <- ensure_table(timezone) do {:ok, Table.unix_to_datetime(table, unix)} end end defp ensure_table(timezone) do case Registry.lookup(TableRegistry, timezone) do [{_pid, table} | _] -> {:ok, table} [] -> case start_child(timezone) do {:ok, _} -> ensure_table(timezone) error -> error end end end defp start_child(timezone) do TableSupervisor.start_child(timezone) end end