3
votes

Coming from Rails Active Record I was wondering how can i actually fetch records which are created today.

In Rails we can do it like this

User.where(created_at:Date.today.beginning_of_day..Date.today.end_of_day)

or much concise

scope :created_today, ->(date = Date.today) { where(created_at: date..date.end_of_day) }

User.created_today

what would be best way to implement same thing with Ecto??

1
What timezone do you want to calculate "today" in? UTC, current system's default, or a specific one?Dogbert
current system's defaultSubhash Chandra

1 Answers

12
votes

Your best bet would be to use the Timex Library.

Using this library you could do something like this:

date = DateTime.today |> Timex.datetime

query = from m in Model, where: m.inserted_at >= ^Timex.beginning_of_day(date), where: m.inserted_at <= ^Timex.end_of_day(date)

Repo.all(query)