NoDisplayName
NoDisplayName

Reputation: 15746

How to compare dates with Elixir and Ecto

I have an instance of Ecto.DateTime that I get from a database column and I need to check if this date is more than 5 minutes in the past.

What is the best way to do that?

To make it more clear, this is what I need in ruby ->

updated_at < (Time.now - 5.minutes)

Upvotes: 20

Views: 3600

Answers (1)

Gazler
Gazler

Reputation: 84180

You can do it using datetime_add/3 using a negative value as the count argument:

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

If you need to do it without using a query you can user the functions in the :calendar erlang module:

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)

Upvotes: 21

Related Questions