Last active
March 23, 2019 01:36
-
-
Save trbngr/de306bfe912fd01bb1395bac84652698 to your computer and use it in GitHub Desktop.
parse dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Dates do | |
@valid_dates [ | |
Date.utc_today() |> Date.to_iso8601(), | |
NaiveDateTime.utc_now() |> NaiveDateTime.to_iso8601(), | |
DateTime.utc_now() |> DateTime.to_iso8601() | |
] | |
|> Enum.map(&to_string/1) | |
|> Enum.join(" or ") | |
@invalid_date_message "Invalid date. Expected formated date. ie #{@valid_dates}" | |
def parse_date(nil), do: {:ok, NaiveDateTime.utc_now()} | |
def parse_date(input) do | |
result = | |
with {:error, _} <- NaiveDateTime.from_iso8601(input), | |
{:error, _} <- DateTime.from_iso8601(input), | |
{:error, _} <- Date.from_iso8601(input) do | |
{:error, @invalid_date_message} | |
end | |
to_naive(result) | |
end | |
defp to_naive({:ok, %NaiveDateTime{} = date}), do: {:ok, date} | |
defp to_naive({:ok, %DateTime{} = date, _offset}), do: {:ok, DateTime.to_naive(date)} | |
defp to_naive({:ok, %Date{day: day, month: month, year: year}}) do | |
{:ok, | |
%NaiveDateTime{ | |
day: day, | |
month: month, | |
year: year, | |
hour: 0, | |
minute: 0, | |
second: 0 | |
}} | |
end | |
defp to_naive(other), do: other | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment