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

2

5

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?

Outwardly answered 25/10, 2016 at 15:12 Comment(2)
Doesn't Ecto.Date.utc/0 work for you? - hexdocs.pm/ecto/Ecto.Date.html#utc/0Celt
Hah. That was the one I was looking for... Thanks.Outwardly
C
5

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

Celt answered 25/10, 2016 at 15:24 Comment(0)
T
3

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

Tom answered 14/6, 2022 at 18:41 Comment(1)
I think that's the best answer up to date.Anarthria

© 2022 - 2024 — McMap. All rights reserved.