Forum: Ruby on Rails Method for returning a random date between two dates

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B4a04ecbe2386b483c36695938f1c320?d=identicon&s=25 Jacob Patton (Guest)
on 2006-01-28 17:57
(Received via mailing list)
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
Bf66e10c8fc4abefebde0425e7f6f15a?d=identicon&s=25 Norman Timmler (Guest)
on 2006-01-28 18:24
(Received via mailing list)
Am Samstag, den 28.01.2006, 11:56 -0500 schrieb Jacob Patton:
> 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
This topic is locked and can not be replied to.