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
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









