Compare Time.now in Rails but ignore year?

2020-02-12 09:41发布

I have the following code in my Rails 3 application:

  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

However, I want to return the results regardless of whether the year matches the current year or not. So long as the day and month match it's fine. Is this possible?

The starts_at and ends_at columns are datetime formatted. So they will automatically include a year even if I dont set one in the form:

<%= f.datetime_select :starts_at, :order => [:day, :month], :discard_year => true %>

Any pointers would be appreciated.

1条回答
太酷不给撩
2楼-- · 2020-02-12 09:44

As Old Pro points out in the comments this does pose a problem with leap years. You likely want to split each dayofyear into MONTH(x) AND DAYOFMONTH(x) instead.


You can use the dayofyear function 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
  }

in mssql it's

datepart(dayofyear,date)

in postgres it's

extract(DOY from date)

in sqlite3 it's

strftime("%j",date)

查看更多
登录 后发表回答