Jacob Patton
2006-Jan-28 16:56 UTC
[Rails] Method for returning a random date between two dates
Hi, I''m trying to create a method to return a random date within a range. So far, I''ve come up with this... require ''parsedate'' def random_date (a, b) adate = ParseDate.parsedate(a) bdate = ParseDate.parsedate(b) atime = Time.local(*adate) btime = Time.local(*bdate) atime + (rand * (atime - btime) ) end ...and it doesn''t seem to work--the dates returned aren''t within the given range. Can anyone spot what I''m doing wrong, or maybe is there a better way to do this? Best, Jacob - Jacob Patton Trisignia http://trisignia.com/ ph: 202-309-1047
Norman Timmler
2006-Jan-28 17:21 UTC
[Rails] Method for returning a random date between two dates
Am Samstag, den 28.01.2006, 11:56 -0500 schrieb Jacob Patton:> require ''parsedate'' > def random_date (a, b) > adate = ParseDate.parsedate(a) > bdate = ParseDate.parsedate(b) > atime = Time.local(*adate) > btime = Time.local(*bdate) > atime + (rand * (atime - btime) ) > end > > ...and it doesn''t seem to work--the dates returned aren''t within the > given range. > > Can anyone spot what I''m doing wrong, or maybe is there a better way to do this?I think you should do (btime - atime) to get the days between those dates. def random_date_between(from, till) from = Date.parse(from) unless from.is_a? Date till = Date.parse(till) unless till.is_a? Date from + rand(till - from) end -- Norman Timmler http://blog.inlet-media.de