Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Time.now in Rails but ignore year?

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.

like image 511
dannymcc Avatar asked Nov 03 '22 22:11

dannymcc


1 Answers

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)

like image 183
Shawn Balestracci Avatar answered Nov 09 '22 05:11

Shawn Balestracci