使用日期不正常的地方。
我似乎无法在我的两个日期中正确地进行日期搜索。
我在搜索模型中使用以下内容搜索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 = ?", 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字段的表单
如果我只输入日期,例如03/24/15,我会得到所有我期望的项目
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)'
我发现我必须修改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> = 2016-03-25