This post originated from an RSS feed registered with Ruby Buzz
by Obie Fernandez.
Original Post: Quickly Generate Random Dates in Ruby
Feed Title: Obie On Rails (Has It Been 9 Years Already?)
Feed URL: http://jroller.com/obie/feed/entries/rss
Feed Description: Obie Fernandez talks about life as a technologist, mostly as ramblings about software development and consulting. Nowadays it's pretty much all about Ruby and Ruby on Rails.
I was poking some random dates manually into my database this morning when I realized there is a better way. The great thing about Ruby is that I was able to code the following little class extension in my head (after all it's only 4 lines). I knew it would work without typing it out, but I typed 'irb' and confirmed a couple of assumptions, after which I committed the following code to a file.
class Time
def self.random(years_back=5)
year = (rand * years_back).ceil + 2000
month = (rand * 12).ceil
day = (rand * 31).ceil
Time.local(year, month, day)
end
end
It's easy to use and obviously gives you more varied results than doing Time.now like most of us do all the time we need a date. Just say Time.random instead. I threw in the option of specifying how many years back it should go, defaulting to 5.
rb(main):001:0> require 'randomtime'
=> true
irb(main):002:0> 10.times { p Time.random }
Wed Nov 13 00:00:00 EST 2002
Sat Dec 11 00:00:00 EST 2004
Thu Mar 17 00:00:00 EST 2005
Tue Apr 10 00:00:00 EDT 2001
Tue Oct 25 00:00:00 EDT 2005
Wed Oct 29 00:00:00 EST 2003
Sun Apr 17 00:00:00 EDT 2005
Sat Apr 13 00:00:00 EDT 2002
Sat Apr 06 00:00:00 EST 2002
Sat Sep 01 00:00:00 EDT 2001
=> 10
I think this little sample is a good example of Ruby's power and expressiveness, if I do say so myself. The whole exercise including typing out this blog entry has taken me about 15 minutes! Enhancements for this code would be to add an option to generate sequences. I'll post that later.
Update:An alert reader suggested a possible improvement would be safer to generate the day number with a factor of 28 instead of 31. Actually, it isn't necessary to guard against a date such as Feb 31, because Ruby turns it into Mar 2 without complaining.