My goal is to find a difference in hours between now and some provided date_time. I'm trying to do this this way:
pry(1)> dt1
#DateTime<2017-10-24 05:12:46.000000Z>
pry(2)> Ecto.DateTime.to_erl(dt1)
** (FunctionClauseError) no function clause matching in Ecto.DateTime.to_erl/1
The following arguments were given to Ecto.DateTime.to_erl/1:
# 1
#DateTime<2017-10-24 05:12:46.000000Z>
Attempted function clauses (showing 1 out of 1):
def to_erl(%Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec})
(ecto) lib/ecto/date_time.ex:608: Ecto.DateTime.to_erl/1
# ............
How to fix that? Or is there a better way to achieve my goal?
Note that I don't use timex and won't use it, neither any third-party library. Only ones built-in in Elixir/Erlang/Phoenix.
You can use DateTime.diff/3
:
iex> dt1 = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "AMT",
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
...> utc_offset: -14400, std_offset: 0, time_zone: "America/Manaus"}
iex> dt2 = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "CET",
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
...> utc_offset: 3600, std_offset: 0, time_zone: "Europe/Warsaw"}
iex> DateTime.diff(dt1, dt2)
18000
iex> DateTime.diff(dt2, dt1)
-18000
Since DateTime.diff/3
returns seconds you have to calculate the hours out of the result like this:
result_in_hours = result_in_seconds/(60*60)
This answer has been added before topic author edited his question and excluded external libs from the scope. However, I'm not deleting it as I find Timex extremely useful and maybe someone will be interested in using it as well (I have nothing to do with Timex creators)
I strongly recommend using Timex library. It's perfect for date/time calculations with different formats and time zones. So in your case to easily calculate hour difference you just need to:
Timex.diff(dt1, DateTime.utc_now, :hours)
You can find diff/3 docs here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With