Rails中的日期范围是否包括边界日期?

时间:2017-06-06 12:52:52

标签: ruby-on-rails ruby range

我想在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

我的范围是否包含这两个边界时间,还是使用<>

1 个答案:

答案 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_dayend_of_day后的几毫秒内发生变化,所以你可以做那么。

today = Time.zone.today
Users.where(created_at: today.beginning_of_day..today.end_of_day)