【问题标题】:best way to get records created today with Ecto Phoenix?今天用 Ecto Phoenix 创建记录的最佳方式是什么?
【发布时间】:2016-06-13 17:20:28
【问题描述】:

来自 Rails Active Record 我想知道如何才能真正获取今天创建的记录。

在 Rails 中我们可以这样做

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

或者更简洁

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

User.created_today

用 Ecto 实现相同功能的最佳方法是什么?

【问题讨论】:

  • 您想在哪个时区计算“今天”? UTC,当前系统的默认值,还是特定的?
  • 当前系统的默认值

标签: elixir phoenix-framework ecto


【解决方案1】:

最好的办法是使用Timex 库。

使用这个库你可以做这样的事情:

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)

【讨论】:

  • 对于那些希望在这种情况下处理给定时区并且您的 datetime 列以 UTC 格式存储的人来说,要对此进行一些扩展,一种方法是:date = date |> Timex.Timezone。 convert("America/Chicago") query = from m in Model,其中:m.inserted_at >= ^Timex.Timezone.convert(Timex.beginning_of_day(date), "UTC"),其中:m.inserted_at
猜你喜欢
  • 2012-09-03
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 2011-07-31
  • 2010-09-06
相关资源
最近更新 更多