Reputation: 113
I am new to elixir community and trying to follow elixir way coding, so i need an advise. How can I get the lowest time diff between two dates in keyword format. For example, if time diff is less then 1 minute than {:seconds, 10}, if time diff is less than one hour, than {:minutes, 34} and so on. So i come up with solution
cmp = %{:seconds => 60, :minutes => 60, :hours => 24, :days => 365, :years => 100}
{_, d} = Timex.parse("2018-01-05T22:25:00-06:00", "{ISO:Extended}")
{type, value} = Enum.map(Map.keys(cmp), &({&1, Timex.diff(Timex.now, d, &1)} ))
|> Enum.filter(fn {k, v} -> v < cmp[k] && v > 0 end)
|> List.first
Could you please point me the right way to achieve my purpose
Upvotes: 0
Views: 344
Reputation: 121000
I believe you are almost done, the only thing I would improve is to walk the other direction, from years downwards. That way you won’t need any numerics:
{:ok, d} = Timex.parse("2018-01-05T22:25:00-06:00", "{ISO:Extended}")
now = Timex.now
unit =
Enum.find(
~w|years days hours minutes seconds|a,
&Timex.diff(now, d, &1) > 0))
{unit, Timex.diff(now, d, unit)}
or, to avoid the subsequent call to Timex.diff/3
, use Enum.find_value/3
:
now = Timex.now
Enum.find_value(~w|years days hours minutes seconds|a, fn unit ->
diff = Timex.diff(now, d, unit)
if diff > 0, do: {unit, diff}
end)
Upvotes: 1