gpt4 book ai didi

datetime - 在Ecto.DateTime和DateTime之间转换

转载 作者:行者123 更新时间:2023-12-04 17:07:35 31 4
gpt4 key购买 nike

我在Ecto.DateTime中有一个日期时间,在日期时间中有第二个日期时间。如何将它们彼此转换?没有外部依赖项,有没有简便的方法?文档中没有任何内容。其中一个使用to_erl,另一个使用from_unix,但是方法之间没有重叠,例如to_unix/from_unix或to_erl/from_erl或类似的方法。

最佳答案

Ecto.DateTime的等效项是NaiveDateTime,因为它们都不存储时区,而DateTime则存储时区。 Erlang日期时间也没有时区,这就是为什么to_erl中没有from_erlDateTime的原因。

您可以先转换为NaiveDateTime,然后将DateTime.from_naive/2以及日期时间所在的时区一起使用(Elixir从Elixir 1.4开始仅支持Etc/UTC):

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

关于datetime - 在Ecto.DateTime和DateTime之间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42104441/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com