我想在Rails中查询日期范围:
User.where(:created_at => Time.now.beginning_of_day..Time.now.end_of_day)
Time.now.beginning_if_day is at 00:00:00
Time.now.end_of_day is at: 23.59.59
我的范围是否包含这两个边界时间,还是使用<
和>
?
答案 0 :(得分:1)
打开好的控制台可以解答所有问题。
..
在db
BETWEEN
语句
User.where(created_at: Time.zone.today.beginning_of_day..Time.zone.today.end_of_day).to_sql
# SELECT "users".*
# FROM "users"
# WHERE ("users"."created_at" BETWEEN '2017-06-06 00:00:00' AND '2017-06-06 23:59:59.999999')
使用...
,它会调用>=
<
魔法。
User.where(created_at: Time.zone.today.beginning_of_day...Time.zone.today.end_of_day).to_sql
# SELECT "users".*
# FROM "users"
# WHERE ("users"."created_at" >= '2017-06-06 00:00:00' AND
# "users"."created_at" < '2017-06-06 23:59:59.999999')
Rails 5.1包含一个名为all_day
的小帮手,这使得这成为可能。它发出与..
Users.where(created_at: Time.zone.today.all_day).to_sql
注意:强>
如果你真的很偏执并且有一个非常重要的救生应用,Time.zone.today
实际上可能会在调用beginning_of_day
和end_of_day
后的几毫秒内发生变化,所以你可以做那么。
today = Time.zone.today
Users.where(created_at: today.beginning_of_day..today.end_of_day)