From f3511788c2445927d58b61fabeedac52065f38ff Mon Sep 17 00:00:00 2001 From: Nick Chmielewski Date: Thu, 11 May 2017 16:03:26 +1000 Subject: [PATCH 1/2] Handle dates that aren't real --- lib/chronic.ex | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/lib/chronic.ex b/lib/chronic.ex index 119ff01..2742ddf 100644 --- a/lib/chronic.ex +++ b/lib/chronic.ex @@ -49,20 +49,36 @@ defmodule Chronic do iex> Chronic.parse("2nd of aug at 9:15 am", currently: {{2016, 1, 1}, {0,0,0}}) { :ok, %NaiveDateTime{day: 2, hour: 9, minute: 15, month: 8, second: 0, microsecond: {0,6}, year: 2016}, 0 } + + iex> Chronic.parse("Feb 29", currently: {{2016, 1, 1}, {0,0,0}}) + { :ok, %NaiveDateTime{day: 29, hour: 0, minute: 0, month: 2, second: 0, microsecond: {0,6}, year: 2016}, 0 } + + iex> Chronic.parse("Feb 29", currently: {{2017, 1, 1}, {0,0,0}}) + { :error, :invalid_datetime } + + iex> Chronic.parse("Nov 31") + { :error, :invalid_datetime } """ def parse(time, opts \\ []) do case Calendar.NaiveDateTime.Parse.iso8601(time) do { :ok, time, offset } -> { :ok, time, offset } _ -> - currently = opts[:currently] || :calendar.universal_time - result = time |> preprocess |> debug(opts[:debug]) |> process(currently: currently) - case result do - { :ok, time } -> - { :ok, time, 0 } - error -> - error - end + parse_natural_language(time, opts) + end + end + + defp parse_natural_language(time_as_string, opts) do + currently = opts[:currently] || :calendar.universal_time + result = try do + time_as_string |> preprocess |> debug(opts[:debug]) |> process(currently: currently) + rescue + e in MatchError -> e.term + end + + case result do + {:ok, datetime = %NaiveDateTime{} } -> { :ok, datetime, 0 } + error -> error end end From c054624f80be3e344da6c2bfe23ada720ab34ffd Mon Sep 17 00:00:00 2001 From: Nick Chmielewski Date: Thu, 11 May 2017 16:27:02 +1000 Subject: [PATCH 2/2] Clean and tighten up parse/2 function --- lib/chronic.ex | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/chronic.ex b/lib/chronic.ex index 2742ddf..12bacce 100644 --- a/lib/chronic.ex +++ b/lib/chronic.ex @@ -61,10 +61,8 @@ defmodule Chronic do """ def parse(time, opts \\ []) do case Calendar.NaiveDateTime.Parse.iso8601(time) do - { :ok, time, offset } -> - { :ok, time, offset } - _ -> - parse_natural_language(time, opts) + result = { :ok, _ = %NaiveDateTime{}, _ } -> result + _ -> parse_natural_language(time, opts) end end