Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: How to get the current date for an Ecto Query?

Tags:

elixir

ecto

It is a bit of a joke that I have to ask this but it is really not clear what the best way is. So this might turn into a little rant. But I have the fealing that Elixir lacks seriously here.

I find it quite complicated to get the current date to query in Ecto agains the current date. For example for something like get me every record where date column x contains a date before t.

As of now I use Erlangs :calendar.universal_time(), pass that to Ecto.DateTime.from_erl and that again to Ecto.Date.cast.

date = :calendar.universal_time() |> Ecto.DateTime.from_erl |> Ecto.Date.cast

Note that we also have to pattern match the actual date, since we get back a tuple

{:ok, #Ecto.Date<2016-10-25>}

So it is

{:ok, date} = :calendar.universal_time() |> Ecto.DateTime.from_erl |> Ecto.Date.cast

Of course I could use Ecto.Date.cast! but that again is something you have to find out and could have some downsides I'm not aware of.

Then I can build the query. But I have to call at least 3 functions everytime...

query = from m in Model, select: {m.name, m.email}, where: (m.canceled_to > ^date), order_by: [desc: m.inserted_at]
result = Repo.all(query)

So is there a better way that I'm missing?

like image 262
Ole Spaarmann Avatar asked Oct 25 '16 15:10

Ole Spaarmann


2 Answers

To get the current date in Ecto - Ecto.Date.utc/0

like image 152
Alex Avoiants Avatar answered Nov 15 '22 09:11

Alex Avoiants


The Ecto.Date module is now depreciated; however, you can use the regular Elixir Date like: ^Date.utc_today().

like image 28
cseagull Avatar answered Nov 15 '22 07:11

cseagull