How to compare dates in rails without a year?

I am trying to find all users with birthdays in the next 2 weeks.

I tried the following:

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

which obviously does not work, because the β€œyear” in the DOB is not equal to this year.

I need to compare only months and days.

How can i do this?

+4
source share
3 answers

Based on Salil's answer, I got 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]) 
+1
source

You need to execute mysql method in dob column

Something like the 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, which 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]) 
+1
source

This can help in changing the date format for comparison, since by default it will accept 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)> 

Make a note if you get a code for direct comparison.

0
source

All Articles