由于不推荐使用Ecto.DateTime,您如何创建新的DateTime?

问题描述 投票:1回答:2

我目前有一个Date和一个Time,我真的想要组合成一个DateTime结构。

在Ecto 3之前,您可以使用Ecto.DateTime.from_date_and_time执行此操作,但在新文档中,因为不推荐使用Ecto类型,所以无法找到等效函数。

该功能目前看起来像:

def add_datetime(date_as_string) do
 (_, date = Date.from_iso8601(date)
 end_time = #T[23:59:59]

 datetime = datetime_add(Ecto.DateTime.from_date_and_time(date, end_time), -3, "day")
end

这个特定项目的一个限制是我想尽可能避免添加像Timex这样的第三方库,但是在查看当前的Elixir文档之后我很遗憾。

elixir phoenix
2个回答
2
投票

你可以使用DateTime.from_iso8601/2

datetime_iso8601 = "#{Date.to_iso8601(date)}T#{Time.to_iso8601(time)}+03:30"
{:ok, datetime, offset_from_utc} = DateTime.from_iso8601(datetime_iso8601)

而不是+3:30使用您想要的偏移量,或Z用于UTC。


0
投票

对于在Google上发现此问题的任何人,如果您不关心时区信息,也可以使用NaiveDateTime

datetime= NaiveDateTime.new(date_struct, time_struct)
|> DateTime.from_naive("Etc/UTC")
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.