~ihabunek/triglav

a28cbc6ce16767b24a2c44f3e16ab43e7fecaa43 — Ivan Habunek a month ago 70283b7
Add helper for parsing HTTP dates
1 files changed, 29 insertions(+), 0 deletions(-)

A lib/triglav/date_time.ex
A lib/triglav/date_time.ex => lib/triglav/date_time.ex +29 -0
@@ 0,0 1,29 @@
defmodule Triglav.DateTime do
  @doc """
  Parse a date-time from HTTP headers in RFC1123 format.

  For example:

      iex> Triglav.DateTime.parse_http_date("Wed, 01 Jun 2022 22:00:02 GMT")
      {:ok, ~U[2022-06-01 22:00:02Z]}
  """
  @spec parse_http_date(String.t()) :: {:ok, DateTime.t()} | {:error, term()}
  def parse_http_date(date) do
    case :hackney_date.parse_http_date(date) do
      {:error, error} ->
        {:error, error}

      {date, time} ->
        with {:ok, date} <- Date.from_erl(date),
             {:ok, time} <- Time.from_erl(time) do
          DateTime.new(date, time)
        end
    end
  end

  @spec parse_http_date!(String.t()) :: DateTime.t()
  def parse_http_date!(date) do
    {:ok, date_time} = parse_http_date(date)
    date_time
  end
end