My goal is to find time difference in minutes:
{_, {_, aaa, _}} = Ecto.DateTime.to_erl(d1) |> :calendar.time_difference(:calendar.universal_time)
I have a timestamp retrieved from Postgresql:
iex(13)> d1
~N[2017-02-09 07:23:04.000000]
Previously this worked well:
d11 = Ecto.DateTime.to_erl(d1)
But now it throws an exception:
* (FunctionClauseError) no function clause matching in Ecto.DateTime.to_erl/1
(ecto) lib/ecto/date_time.ex:608: Ecto.DateTime.to_erl(~N[2017-02-09 07:23:04.000000])
How to fix that?
I'm not willing to use external libraries such as times.
For some reason, the DateTime
value you have in RDBMS lacks the timezone information. There is a main difference between Ecto.DateTime
and NaiveDateTime
: the former cares about timezones, and the latter does not (as well as standard erlang datetime.)
iex(1)> d1 = ~N[2017-02-09 07:23:04.000000]
~N[2017-02-09 07:23:04.000000]
iex(2)> NaiveDateTime.to_erl d1
{{2017, 2, 9}, {7, 23, 4}}
From the snippet above one might see, that the conversion is still possible with NaiveDateTime.to_erl/1
.
The core solution would be to find the cause of having naïve datetime value in the RDBMS and fix it.