Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto.Datetime get 15 minutes ago

Tags:

elixir

ecto

Ecto.DateTime.utc returns current datetime.

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

like image 588
asiniy Avatar asked Sep 07 '25 18:09

asiniy


2 Answers

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.

like image 94
Dogbert Avatar answered Sep 11 '25 00:09

Dogbert


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.

like image 36
willc0de4food Avatar answered Sep 11 '25 01:09

willc0de4food