Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates with Elixir and Ecto

Tags:

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)
like image 604
NoDisplayName Avatar asked Aug 31 '15 10:08

NoDisplayName


1 Answers

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)
like image 186
Gazler Avatar answered Sep 29 '22 10:09

Gazler