在 Rails 中比较 Time.now 但忽略年份? [英] Compare Time.now in Rails but ignore year?

查看:24
本文介绍了在 Rails 中比较 Time.now 但忽略年份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Rails 3 应用程序中有以下代码:

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?

starts_atends_at 列采用 datetime 格式.因此,即使我没有在表单中设置年份,它们也会自动包含一年:

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 %>

任何指针将不胜感激.

推荐答案

正如 Old Pro 在评论中指出的那样,这确实会带来闰年的问题.您可能希望将每年的每一天拆分为 MONTH(x) 和 DAYOFMONTH(x).

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.

可以使用dayofyear函数https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofyear

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
  }

mssql 中是

datepart(dayofyear,date)

datepart(dayofyear,date)

postgres这是

提取(从日期开始)

sqlite3

strftime("%j",date)

strftime("%j",date)

这篇关于在 Rails 中比较 Time.now 但忽略年份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆