Alex Antonov
Alex Antonov

Reputation: 15146

Ecto.Datetime get 15 minutes ago

Ecto.DateTime.utc returns current datetime.

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

Upvotes: 4

Views: 1496

Answers (2)

willc0de4food
willc0de4food

Reputation: 23

For anyone landing here in 2023, Elixir's DateTime module has an add() function which does accept negative numbers, so you could do something like:

DateTime.add(DateTime.utc_now(), -15, :minute)

See the hexdocs for the full definition and options.

Upvotes: 1

Dogbert
Dogbert

Reputation: 222098

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.

Upvotes: 7

Related Questions