如何比较 Phoenix/Ecto 中 2 个日期的分钟数?
How to compare minutes in 2 dates in Phoenix/Ecto?
我想找出 "utc now" 和 Ecto.DateTime
类型变量之间的时间差(以分钟为单位)。最简单的方法是什么?我是否应该在 unix 时间中转换它们并减去而不是先进行模式匹配和比较年、月、日和小时,然后才实际减去分钟?我不打算使用任何第三方依赖项。
JIC:Ecto.DateTime
is a struct and it has a Ecto.DateTime.from_erl/1
helper (as well as from_unix!
and some others.) It also is responsible for generating “utc now” with Ecto.DateTime.utc/1
.
长生不老药 DateTime
又 to_unix/2
,因此可能:
dt1, dt2 = [ecto_time, Ecto.DateTime.utc]
|> Enum.map(&Ecto.DateTime.to_erl/1)
|> Enum.map(&NaiveDateTime.from_erl!/1)
|> Enum.map(&DateTime.from_naive!(&1, "Etc/UTC"))
|> Enum.map(&DateTime.to_unix(&1))
mins = (dt1 - dt2) / 60
您可以使用 UTC 时区将 Ecto.DateTime
转换为 DateTime
,然后比较它们的 to_unix
:
iex(1)> now = DateTime.utc_now |> DateTime.to_unix
1486544161
iex(2)> now2 = Ecto.DateTime.utc |> Ecto.DateTime.to_erl |> NaiveDateTime.from_erl! |> DateTime.from_naive!("Etc/UTC") |> DateTime.to_unix
1486544206
iex(3)> (now2 - now) / 60
0.75
模式匹配不是一个好主意,因为您必须处理 year/month/day/hour/minute/second 在 adding/subtracting 之后溢出的所有情况。
Elixir 现在有一个 DateTime.diff/3
方法。
DateTime.diff(dt1, dt2, :minute)
(在你的情况下 dtx 是 DateTime.utc_now
)
我想找出 "utc now" 和 Ecto.DateTime
类型变量之间的时间差(以分钟为单位)。最简单的方法是什么?我是否应该在 unix 时间中转换它们并减去而不是先进行模式匹配和比较年、月、日和小时,然后才实际减去分钟?我不打算使用任何第三方依赖项。
JIC:Ecto.DateTime
is a struct and it has a Ecto.DateTime.from_erl/1
helper (as well as from_unix!
and some others.) It also is responsible for generating “utc now” with Ecto.DateTime.utc/1
.
长生不老药 DateTime
又 to_unix/2
,因此可能:
dt1, dt2 = [ecto_time, Ecto.DateTime.utc]
|> Enum.map(&Ecto.DateTime.to_erl/1)
|> Enum.map(&NaiveDateTime.from_erl!/1)
|> Enum.map(&DateTime.from_naive!(&1, "Etc/UTC"))
|> Enum.map(&DateTime.to_unix(&1))
mins = (dt1 - dt2) / 60
您可以使用 UTC 时区将 Ecto.DateTime
转换为 DateTime
,然后比较它们的 to_unix
:
iex(1)> now = DateTime.utc_now |> DateTime.to_unix
1486544161
iex(2)> now2 = Ecto.DateTime.utc |> Ecto.DateTime.to_erl |> NaiveDateTime.from_erl! |> DateTime.from_naive!("Etc/UTC") |> DateTime.to_unix
1486544206
iex(3)> (now2 - now) / 60
0.75
模式匹配不是一个好主意,因为您必须处理 year/month/day/hour/minute/second 在 adding/subtracting 之后溢出的所有情况。
Elixir 现在有一个 DateTime.diff/3
方法。
DateTime.diff(dt1, dt2, :minute)
(在你的情况下 dtx 是 DateTime.utc_now
)