Skip to content

Commit 331be2e

Browse files
committed
Handle dates that aren't real
1 parent 71d4539 commit 331be2e

1 file changed

Lines changed: 25 additions & 8 deletions

File tree

lib/chronic.ex

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,20 +49,37 @@ defmodule Chronic do
4949
5050
iex> Chronic.parse("2nd of aug at 9:15 am", currently: {{2016, 1, 1}, {0,0,0}})
5151
{ :ok, %NaiveDateTime{day: 2, hour: 9, minute: 15, month: 8, second: 0, microsecond: {0,6}, year: 2016}, 0 }
52+
53+
iex> Chronic.parse("Feb 29", currently: {{2016, 1, 1}, {0,0,0}})
54+
{ :ok, %NaiveDateTime{day: 29, hour: 0, minute: 0, month: 2, second: 0, microsecond: {0,6}, year: 2016}, 0 }
55+
56+
iex> Chronic.parse("Feb 29", currently: {{2017, 1, 1}, {0,0,0}})
57+
{ :error, :invalid_datetime }
58+
59+
iex> Chronic.parse("Nov 31")
60+
{ :error, :invalid_datetime }
5261
"""
5362
def parse(time, opts \\ []) do
5463
case Calendar.NaiveDateTime.Parse.iso8601(time) do
5564
{ :ok, time, offset } ->
5665
{ :ok, time, offset }
5766
_ ->
58-
currently = opts[:currently] || :calendar.universal_time
59-
result = time |> preprocess |> debug(opts[:debug]) |> process(currently: currently)
60-
case result do
61-
{ :ok, time } ->
62-
{ :ok, time, 0 }
63-
error ->
64-
error
65-
end
67+
parse_natural_language(time, opts)
68+
end
69+
end
70+
71+
defp parse_natural_language(time_as_string, opts) do
72+
currently = opts[:currently] || :calendar.universal_time
73+
try do
74+
result = time_as_string |> preprocess |> debug(opts[:debug]) |> process(currently: currently)
75+
case result do
76+
{:ok, datetime = %NaiveDateTime{} } ->
77+
{ :ok, datetime, 0 }
78+
error ->
79+
error
80+
end
81+
rescue
82+
e in MatchError -> e.term
6683
end
6784
end
6885

0 commit comments

Comments
 (0)