Search code examples
elixirecto

Ecto.Datetime get 15 minutes ago


Ecto.DateTime.utc returns current datetime.

How can I create Ecto.DateTime for 15 minutes ago?


Solution

  • Get the time using :erlang.universaltime (Ecto uses this for Ecto.DateTime.utc/0), convert to gregorian seconds using :calendar, subtract 15 * 60, convert back to an Erlang Time tuple, and cast back to Ecto.DateTime:

    iex(1)> utc = :erlang.universaltime |> :calendar.datetime_to_gregorian_seconds
    63638236105
    iex(2)> fifteen_minutes_ago = (utc - 15 * 60) |> :calendar.gregorian_seconds_to_datetime |> Ecto.DateTime.cast!
    #Ecto.DateTime<2016-08-12 15:33:25>
    

    Edit: a pipeline might look better here:

    :erlang.universaltime
    |> :calendar.datetime_to_gregorian_seconds
    |> Kernel.-(15 * 60)
    |> :calendar.gregorian_seconds_to_datetime
    |> Ecto.DateTime.cast!
    |> IO.inspect
    

    Same output as before.