如何比较不带年份的 Rails 中的日期?

发布于 2024-12-04 01:57:34 字数 240 浏览 2 评论 0原文

我正在尝试找到未来两周内生日的所有用户。

我尝试了以下方法:

User.find(:all, :conditions => ["DOB > ? and DOB <= ?", Date.today, 2.weeks.from_now])

这显然不起作用,因为 DOB 中的“年份”不等于今年。

我只需要比较月份和日期。

我该怎么做呢?

I'm trying to find all users with birthdays in the coming 2 weeks.

I tried the following:

User.find(:all, :conditions => ["DOB > ? and DOB <= ?", Date.today, 2.weeks.from_now])

which obviously doesn't work because the 'year' in the DOB doesn't equal to this year.

I need to only compare the months and the days.

How can I go about doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

无所谓啦 2024-12-11 01:57:34

您必须在您的 dob 列上执行 mysql 方法

,如下所示

  SELECT FROM users  
         WHERE DAYOFYEAR(dob)in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)

您可以使用 WEEK 等适合您的函数参考 this 用于

ruby​​ 中的mysql 函数

arr=[]
(0..13).each{|i| arr << (Date.today+i.day).day }
User.find(:all, :conditions => ["DAYOFYEAR(DOB) in (?)", arr])

You have to perform mysql method on your dob column

Something like following

  SELECT FROM users  
         WHERE DAYOFYEAR(dob)in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)

You can use functions like WEEK whichever works for you Ref this for mysql function

In ruby

arr=[]
(0..13).each{|i| arr << (Date.today+i.day).day }
User.find(:all, :conditions => ["DAYOFYEAR(DOB) in (?)", arr])
§普罗旺斯的薰衣草 2024-12-11 01:57:34

根据 Salil 的回答,我得出以下结论以使其适用于 sqlite:

arr = []
(0..14).each { |i| arr << (Date.today + i.day).yday }
@users = User.find(:all, :conditions => ["cast(strftime('%j', DOB) AS int) in (?)", arr])

Based on Salil's answer, I have derived the following to make it work for sqlite:

arr = []
(0..14).each { |i| arr << (Date.today + i.day).yday }
@users = User.find(:all, :conditions => ["cast(strftime('%j', DOB) AS int) in (?)", arr])
泡沫很甜 2024-12-11 01:57:34

postgresql 的另一种方法:

scope :with_bday, -> (from, to) {
    where("EXTRACT(DOY FROM birthday)::int BETWEEN ? AND ?", *[
        from.yday,
        to.yday
    ])
}

Another aproach for postgresql:

scope :with_bday, -> (from, to) {
    where("EXTRACT(DOY FROM birthday)::int BETWEEN ? AND ?", *[
        from.yday,
        to.yday
    ])
}
羞稚 2024-12-11 01:57:34

这可能有助于更改比较的日期格式,因为默认情况下它将采用 Date.today.year。

              Date.strptime("{ #{DOB.month}, #{DOB.date} }", "{ %m, %d }").

Date.strptime("{ 9, 10 }", "{ %m, %d }")

<Date: 2011-09-10 (4911629/2,0,2299161)>

如果您获得一些用于直接比较的代码,则给出 Do post 。

This may help in changing the date format for comparison as by default it will take Date.today.year.

              Date.strptime("{ #{DOB.month}, #{DOB.date} }", "{ %m, %d }").

Date.strptime("{ 9, 10 }", "{ %m, %d }") gives

<Date: 2011-09-10 (4911629/2,0,2299161)>

Do post if you get some code for direct comparison.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文