无法再转换 Ecto.DateTime.to_erl

No longer able to convert Ecto.DateTime.to_erl

我的目标是找出以分钟为单位的时差:

 {_, {_, aaa, _}} = Ecto.DateTime.to_erl(d1) |> :calendar.time_difference(:calendar.universal_time)

我有一个从 Postgresql 检索到的时间戳:

iex(13)> d1
~N[2017-02-09 07:23:04.000000]

以前这很好用:

d11 = Ecto.DateTime.to_erl(d1)

但现在它抛出一个异常:

* (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])

如何解决?

不太愿意使用times等外部库

出于某种原因,您在 RDBMS 中的 DateTime 值缺少时区信息。 Ecto.DateTime and NaiveDateTime 之间有一个主要区别:前者关心时区,后者不关心(以及标准的 erlang 日期时间。)

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

从上面的代码片段可以看出,使用 NaiveDateTime.to_erl/1 仍然可以进行转换。

核心解决方案是找到 RDBMS 中具有原始日期时间值的原因并修复它。