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 

What is going wrong here?

</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

1 Like

Can you please tell me how does and structural comparison work?

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 :slight_smile:

So, is the Naive DateTime basically a map?

Yes, as any other struct.

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.


Thank you :blush:

1 Like