在Ecto.DateTime和DateTime之间转换

Kot*_*taa 5 datetime elixir ecto phoenix-framework

我在Ecto.DateTime中有一个日期时间,在DateTime中有第二个日期时间.我怎样才能将它们互相转换?没有外部依赖是不是一种简单的方法?文档中没有任何内容.其中一个有to_erl,另一个是from_unix,但方法中没有重叠,例如to_unix/from_unix或to_erl/from_erl或类似的东西.

Dog*_*ert 11

相当于Ecto.DateTimeNaiveDateTime的,因为他们都没有存储时区,而DateTime做.Erlang日期时间也没有时区,这就是为什么没有to_erlfrom_erlin DateTime.

您可以先转换为NaiveDateTime然后使用DateTime.from_naive/2您的日期时间所在的时区(Elixir仅支持Etc/UTCElixir 1.4):

iex(1)> Ecto.DateTime.utc |> Ecto.DateTime.to_erl |> NaiveDateTime.from_erl! |> DateTime.from_naive!("Etc/UTC")
%DateTime{calendar: Calendar.ISO, day: 8, hour: 4, microsecond: {0, 0},
 minute: 49, month: 2, second: 9, std_offset: 0, time_zone: "Etc/UTC",
 utc_offset: 0, year: 2017, zone_abbr: "UTC"}
iex(2)> DateTime.utc_now |> DateTime.to_naive |> NaiveDateTime.to_erl |> Ecto.DateTime.from_erl
#Ecto.DateTime<2017-02-08 04:50:23>
Run Code Online (Sandbox Code Playgroud)

如果您之前使用Ecto.DateTime过,您可能想立即使用NaiveDateTime.