【问题标题】:Converting between Ecto.DateTime and DateTime在 Ecto.DateTime 和 DateTime 之间转换
【发布时间】:2017-06-25 13:24:17
【问题描述】:

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

【问题讨论】:

    标签: datetime elixir phoenix-framework ecto


    【解决方案1】:

    Ecto.DateTime 的等价物是 NaiveDateTime,因为它们都不存储时区,而 DateTime 存储。 Erlang 日期时间也没有时区,这就是为什么 DateTime 中没有 to_erlfrom_erl

    您可以先转换为NaiveDateTime,然后使用DateTime.from_naive/2 以及您的日期时间所在的时区(Elixir 仅支持Etc/UTC,从 Elixir 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>
    

    如果您之前使用的是Ecto.DateTime,那么您现在可能想使用NaiveDateTime

    【讨论】:

      猜你喜欢
      • 2012-11-22
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多