shijith.k
Naive Datetime values comparison using < and > operators
Is it not a right method to compare naive date time values using basic operators like > and < ?
I get wrong answers when I compare two date time values using these operators.
iex(1)> datetime1 = ~N[2019-09-26 01:00:00.000000]
iex(2)> datetime2 = ~N[2020-01-24 00:00:00.000000]
iex(3)> datetime1 > datetime2
true
What is going wrong here?
Marked As Solved
NobbZ
</2 and >/2 work as expected and documented here.
They do a structural comparison. If you want to do a value comparison of those, please use NaiveDateTime.compare/2
Also Liked
Nicd
You can take a peek at the internal structure by using IO.inspect/2 and it’s option structs:
iex(7)> NaiveDateTime.utc_now() |> IO.inspect(structs: false)
%{
__struct__: NaiveDateTime,
calendar: Calendar.ISO,
day: 17,
hour: 12,
microsecond: {614456, 6},
minute: 37,
month: 9,
second: 47,
year: 2019
}
That’s how all structs work in Elixir.
garrison
Structural comparison of dates was actually used as an example of the new type system when it was introduced! At the moment I don’t believe it can catch this within a function like Enum.min_by() (obviously since it didn’t for you), but there are more type system changes coming in 1.19 and 1.20 which have to do with functions, so perhaps it will eventually?
billylanchantin
Yes: CompareChain — compare_chain v0.6.0
The OP would be:
import CompareChain
datetime1 = ~N[2019-09-26 01:00:00.000000]
datetime2 = ~N[2020-01-24 00:00:00.000000]
compare?(datetime1 > datetime2, NaiveDateTime) #=> false
NobbZ
From the erlang documentation:
Maps are ordered by size, two maps with the same size are compared by keys in ascending term order and then by values in key order. In maps key order integers types are considered less than floats types.
LostKobrakai
This means in structural comparison the :day key has precedence over the :month key. So for any value in :month the higher :day value will sort last.







