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?
NobbZ
September 17, 2019, 12:00pm
2
</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
2 Likes
Can you please tell me how does NaiveDateTime.compare/2
and structural comparison work?
NobbZ
September 17, 2019, 12:07pm
4
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.
1 Like
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.
1 Like
ok, that helps
So, is the Naive DateTime basically a map?
NobbZ
September 17, 2019, 12:16pm
7
Yes, as any other struct.
Nicd
September 17, 2019, 12:38pm
8
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.
2 Likes