开发者

How do I compare dates in rails without the year?

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?


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])


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])


Another aproach for postgresql:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜