在Rails中比较Time.now但忽略年份?

dan*_*mcc 5 time activerecord date ruby-on-rails-3

我在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
Run Code Online (Sandbox Code Playgroud)

但是,无论年份是否与当前年份匹配,我都希望返回结果.只要日和月匹配就好了.这可能吗?

starts_atends_atdatetime格式化.因此,即使我没有在表单中设置一个,它们也会自动包含一年:

<%= f.datetime_select :starts_at, :order => [:day, :month], :discard_year => true %>
Run Code Online (Sandbox Code Playgroud)

任何指针将不胜感激.

Sha*_*cci 2

正如老专业人士在评论中指出的那样,这确实造成了闰年的问题。您可能希望将一年中的每一天拆分为 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
  }
Run Code Online (Sandbox Code Playgroud)

mssql中是

日期部分(年份,日期)

postgres中它是

提取(DOY 从日期)

sqlite3中是

strftime("%j",日期)