我的两个日期似乎无法使日期搜索正常工作。
我在搜索模型中使用以下内容搜索created_at日期。
# -------------------------- Begin created at dates ----------------------------
# Only one date is filled in:
documents = documents.where("documents.created_at >= ?", from_date) if from_date.present? and not to_date.present?
documents = documents.where("documents.created_at <= ?", to_date - 1.day) if to_date.present? and not from_date.present?
# Both Dates are filled in
documents = documents.where("documents.created_at >= ?", from_date,) if from_date.present? and to_date.present?
documents = documents.where("documents.created_at <= ?", to_date) if to_date.present? and from_date.present?
请注意,我尝试了to_date - 1.day
的几种变体,例如to_date
和to_date + 1.day
我有一个包含from_date和to_date
字段的表单如果我只输入日期,例如2015年3月24日,我得到了我期望的所有项目,例如
2016-03-24
id Subject Category Author Date Created Date Updated
32 Test Of Dates Test Christopher Mendla 03/24/16 16:45 03/24/16 16:45 Edit
33 Friday Test Christopher Mendla 03/25/16 09:21 03/25/16 09:21
IOW,它按预期工作。
但是,如果我将to_date设置为03/25/16,除了在3/25/16创建的记录之外,我将获得所有记录。如果我搜索03/26/16的to_date,则包含created_at为3/25/16的记录。
我在application.rb中添加了以下内容,但请注意在设置时区之前存在此问题(是的,我知道数据以外的其他格式会导致问题,但这些是内部应用程序,其他工具将用于来自SQL的报告。)
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = 'Eastern Time (US & Canada)'
答案 0 :(得分:0)
我发现我必须修改SQL语句以将存储的日期/时间更改为日期。数据库位于MS Sql Server上。
# -------------------------- Begin created at dates ----------------------------
# Only one date is filled in:
documents = documents.where("documents.created_at >= ?", from_date) if from_date.present? and not to_date.present?
documents = documents.where("cast (documents.created_at as date) <= ?", to_date) if to_date.present? and not from_date.present?
# cast ([created_at] as date) <= '2016-03-25'
# Both Dates are filled in
documents = documents.where("documents.created_at >= ?", from_date,) if from_date.present? and to_date.present?
documents = documents.where("cast (documents.created_at as date) <= ?", to_date) if to_date.present? and from_date.present?
cast (documents.created_at as date)
会将日期作为日期进行比较,并忽略时间。显然2016-03-25 11:40的存储日期不小于或等于2016-03-25。
我没有使用演员作为日期,因为我相信2016-03-25 11:40 IS&gt; = 2016-03-25