【问题标题】:Compare Time.now in Rails but ignore year?比较 Rails 中的 Time.now 但忽略年份?
【发布时间】:2013-05-03 10:43:32
【问题描述】:

我的 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_atends_at 列采用 datetime 格式。所以即使我没有在表格中设置一年,它们也会自动包含一年:

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

任何指针将不胜感激。

【问题讨论】:

  • 可能需要直接执行 SQL。
  • 您使用的是哪个 RDBMS?
  • 我想这意味着数据库类型?如果是这样,mySQL
  • 解决方案取决于您希望如何处理 2 月 29 日。

标签: ruby-on-rails-3 date activerecord time


【解决方案1】:

正如 Old Pro 在 cmets 中指出的那样,这确实对闰年造成了问题。您可能希望将每年的每一天拆分为 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

日期部分(年份,日期)

postgres

提取(从日期开始)

sqlite3

strftime("%j",日期)

【讨论】:

  • @dannymcc 请注意,将闰年 2 月 28 日之后的日期与非闰年的日期进行比较时,这将失败(根据 OP 规定的目标)。此代码将具有 1-MAR-2000 == 2-MAR-2001。
猜你喜欢
  • 1970-01-01
  • 2014-05-02
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多