ecto icon indicating copy to clipboard operation
ecto copied to clipboard

Date comparison

Open chinh7 opened this issue 11 years ago • 7 comments

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 

chinh7 avatar Aug 02 '15 08:08 chinh7

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.

b0oh avatar Aug 02 '15 08:08 b0oh

I will improve the docs, but Ecto.Date and Ecto.DateTime and friends are not comparable.

josevalim avatar Aug 02 '15 10:08 josevalim

Thanks that makes sense. For now I'll convert those to timestamps before comparing

chinh7 avatar Aug 02 '15 10:08 chinh7

@josevalim Is there any way to override the comparison operators for an specific struct?

jonhkr avatar Aug 02 '15 11:08 jonhkr

No. You should provide your own comparison functions.

josevalim avatar Aug 02 '15 11:08 josevalim

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.

josevalim avatar Aug 02 '15 11:08 josevalim

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

nate-tsai avatar Aug 04 '16 06:08 nate-tsai