defmodule HTTPDate do
def now(calendar \\ Calendar.ISO) do
calendar |> DateTime.utc_now() |> from_date_time()
end
def from_date_time(date_time = %DateTime{}) when date_time.utc_offset == 0 do
{
{date_time.year, date_time.month, date_time.day},
{date_time.hour, date_time.minute, date_time.second}
}
|> :httpd_util.rfc1123_date()
end
def from_date_time(other), do: raise("expected a DateTime in UTC (GMT), got: #{inspect(other)}")
def to_date_time(string, calendar \\ Calendar.ISO) do
with {{year, month, day}, {hour, minute, second}} <- :httpd_util.convert_request_date(string),
{:ok, date} <- Date.new(year, month, day, calendar),
{:ok, time} <- Time.new(hour, minute, second, {0, 0}, calendar) do
DateTime.new(date, time, "Etc/UTC")
else
# Normalize :httpd_util.convert_request_date errors
:bad_date -> {:error, :invalid_date}
# Date/Time/DateTime.new errors
{:error, reason} -> {:error, reason}
end
end
end