Date comparison
I was playing around with IEx when I found out Ecto.DateTime comparison is inconsistent with that of Erlang {date, time} tuple. How does Ecto.DateTime comparison work?
iex(58)> a = Ecto.DateTime.from_erl({{2015, 7, 28}, {18, 42, 39}})
#Ecto.DateTime<2015-07-28T18:42:39Z>
iex(59)> e = Ecto.DateTime.from_erl({{2015, 8, 2}, {0, 0, 0}})
#Ecto.DateTime<2015-08-02T00:00:00Z>
iex(60)> a > e
true # shouldn't this be false?
iex(61)> {{2015, 7, 28}, {18, 42, 39}} > {{2015, 8, 2}, {0, 0, 0}}
false
Ecto.Datetime is an elixir struct which implemented using erlang map, when you do Ecto.DateTime.from_erl({{2015, 7, 28}, {18, 42, 39}}) it creates a map %{year: 2015, month: 7, day: 28, hour: 18, min: 42, sec: 39, usec: 0} and Ecto.DateTime.from_erl({{2015, 8, 2}, {0, 0, 0}}) creates %{year: 2015, month: 8, day: 2, hour: 0, min: 0, sec: 0, usec: 0}, if you try to compare it you will see it sorts key alphabetically and day becomes first.
To compare two datetimes I usually transform them to timestamps.
I will improve the docs, but Ecto.Date and Ecto.DateTime and friends are not comparable.
Thanks that makes sense. For now I'll convert those to timestamps before comparing
@josevalim Is there any way to override the comparison operators for an specific struct?
No. You should provide your own comparison functions.
If someone want to provide a compare function to Ecto.Date, Ecto.Time and Ecto.DateTime, it would be a welcome addition. It should require :eq, :lt or :gt.
The Elixir Date struct has the same problem...
iex(1)> d1 = ~D[2016-08-01]
~D[2016-08-01]
iex(2)> d2 = ~D[2016-08-02]
~D[2016-08-02]
iex(3)> d3 = ~D[2016-07-02]
~D[2016-07-02]
iex(4)> d1 < d2
true
iex(5)> d3 < d1
false