在Ruby on Rails中搜索时间范围

时间:2018-02-06 02:32:41

标签: ruby-on-rails ruby

如何查找当天4 am到第二天4 am的记录。困难的部分是2 am我正在寻找前一天4 am到当天4 am的记录。在4:01 am,我正在寻找当天4 am到第二天4 am的记录。

可以这样做吗?

start_time = 4AM
end_time = 4AM
found_attendance_record = Volunteer::Attendance.where(volunteer_id: params[:id], in: start_time..end_time))`

3 个答案:

答案 0 :(得分:1)

如果您想查找当天凌晨4点到次日凌晨4点的记录,请执行以下操作:

start_time = Date.today.to_time + 4.hours
end_time = start_time + 1.day

found_attendance_record = Volunteer::Attendance.where(volunteer_id: params[:id], your_datetime_column: start_time..end_time)

希望这有帮助。

答案 1 :(得分:0)

t1=DateTime.now.in_time_zone('UTC').change({hour:4, min:0, sec:0})
t2=t1 + 24.hours
found_attendance_record = Volunteer::Attendance.where(created_at: t1..t2)

答案 2 :(得分:0)

好的,请尝试以下

创建小时

 start_time = "04:00:00"
 start_time = start_time.to_time
 #=> 2018-02-06 04:00:00 +0000  # it's showing current date 4 AM

现在你可以加24小时

end_time = start_time + 24.hours
#=>  2018-02-07 04:00:00 +0000 # it's showing plus one day 4 am

现在您可以开始查询

found_attendance_record = Volunteer::Attendance.where(volunteer_id: params[:id], in: start_time..end_time))

希望有所帮助