我的 Rails 3 应用程序中有以下代码:
scope :active, lambda {
where("starts_at <= ? AND ends_at >= ?", Time.now.utc, Time.now.utc)
}
scope :since, lambda { |hide_time|
where("updated_at > ? OR starts_at > ?", hide_time.utc, hide_time.utc) if hide_time
}
def self.display(hide_time)
active.since(hide_time)
end
但是,无论年份是否与当前年份匹配,我都想返回结果。只要日期和月份匹配就可以了。这可能吗?
starts_at
和 ends_at
列是 datetime
格式化。因此,即使我没有在表单中设置一年,它们也会自动包含一年:<%= f.datetime_select :starts_at, :order => [:day, :month], :discard_year => true %>
任何指针将不胜感激。
最佳答案
正如 Old Pro 在评论中指出的那样,这确实对闰年造成了问题。您可能希望将每一年的每一天拆分为 MONTH(x) 和 DAYOFMONTH(x)。
您可以使用 dayofyear 功能
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofyear
scope :active, lambda {
where("dayofyear(starts_at) <= dayofyear(?) AND
dayofyear(ends_at) >= dayofyear(?)", Time.now.utc, Time.now.utc)
}
scope :since, lambda { |hide_time|
where("dayofyear(updated_at) > dayofyear(?) OR
dayofyear(starts_at) > dayofyear(?)", hide_time.utc, hide_time.utc) if hide_time
}
在 mssql它是
datepart(dayofyear,date)
在 postgres它是
extract(DOY from date)
在 sqlite3它是
strftime("%j",date)
关于ruby-on-rails-3 - 在 Rails 中比较 Time.now 但忽略年份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16357033/