Reputation: 529
in my app I need to set up the timeout for operation. Thanks to Timex library, it's easy to do.
Sadly, I got a strange error. I dig it and found this:
iex(55)> dt = Timex.now() |> Timex.add( Timex.Duration.from_seconds( 10))
#DateTime<2017-12-13 18:32:30.922418Z>
iex(56)> DateTime.utc_now()
#DateTime<2017-12-13 18:32:22.411246Z>
iex(57)> dt <= DateTime.utc_now()
false
iex(58)> dt <= DateTime.utc_now()
false
iex(59)> dt <= DateTime.utc_now()
false
iex(60)> dt <= DateTime.utc_now()
false
iex(61)> dt <= DateTime.utc_now()
false
iex(62)> dt <= DateTime.utc_now()
false (!)
iex(63)> dt <= DateTime.utc_now()
true (!)
iex(64)> dt <= DateTime.utc_now()
false (!)
iex(65)> dt <= DateTime.utc_now()
false
iex(66)> dt <= DateTime.utc_now()
false
What I'm doing wrong? Is it a bug, or it meant to be like this? What is the right choice to compare two datetime's in Elixir?
PS> I'm using Elixir 1.5.2.
Erlang/OTP 20 [erts-9.0.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Upvotes: 1
Views: 2703
Reputation: 222098
You cannot use the comparison operators with DateTime
. To those operators, a DateTime
struct is just a map which doesn't compare how you'd want to compare DateTime
s (years, then month, then day, and so on). You can use DateTime.compare/2
for this:
iex(1)> {:ok, dt1, 0} = DateTime.from_iso8601("2017-12-13 18:32:30.922418Z")
{:ok, #DateTime<2017-12-13 18:32:30.922418Z>, 0}
iex(2)> {:ok, dt2, 0} = DateTime.from_iso8601("2017-12-13 18:32:22.411246Z")
{:ok, #DateTime<2017-12-13 18:32:22.411246Z>, 0}
iex(3)> DateTime.compare(dt1, dt2)
:gt
iex(4)> DateTime.compare(dt2, dt1)
:lt
Upvotes: 7