如何比较Elixir和Ecto的日期

NoD*_*ame 19 elixir ecto phoenix-framework

我有一个Ecto.DateTime来自数据库列的实例,我需要检查这个日期是否超过5分钟.

最好的方法是什么?

为了更清楚,这是我在ruby中所需要的 - >

updated_at < (Time.now - 5.minutes)
Run Code Online (Sandbox Code Playgroud)

Gaz*_*ler 20

您可以使用负值作为参数使用datetime_add/3来执行此操作count:

from u in User,
  where: u.reset_password_sent_at > datetime_add(^Ecto.DateTime.utc, -5, "minute")
Run Code Online (Sandbox Code Playgroud)

如果您需要在不使用查询的情况下执行此操作,则可以使用:calendar erlang模块中的函数:

ecto_5_mins_ago =
  Ecto.DateTime.utc
  |> Ecto.DateTime.to_erl
  |> :calendar.datetime_to_gregorian_seconds
  |> Kernel.-(60 * 5)
  |> :calendar.gregorian_seconds_to_datetime
  |> Ecto.DateTime.from_erl

Ecto.DateTime.compare(u.reset_password_token, ecto_5_mins_ago)
Run Code Online (Sandbox Code Playgroud)

  • 你可能想看看https://github.com/bitwalker/timex然后:) (7认同)
  • 我很惊讶这种东西没有一些方便的内置功能,但无论如何谢谢你 (3认同)