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

查看:66
本文介绍了比较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_at ends_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 %>

任何指针都会受到赞赏。

Any pointers would be appreciated.

推荐答案

正如Old Pro在评论中指出的那样,这确实给leap年带来了问题。您可能希望将每年的每一天拆分为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,日期)

datepart(dayofyear,date)

postgres 它是


extract(从日期开始, )

extract(DOY from date)

sqlite3


strftime(%j,date)

strftime("%j",date)

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

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