Range of date in Ruby

I needed to select a random date within a range… I figured out this is very easy in ruby 🙂

Let’s say I want to be able to select a random date between « today – 15 days » and « today + 15 days ».
Here is a snippet that describes the thing:

require 'date'
today = DateTime.now
new_date = (today-15..today+15).to_a[rand(15)-15]


irb(main):010:0> today.strftime("%a %d/%m/%y %H:%M")
=> "Thu 25/02/10 11:33"
irb(main):011:0> new_date.strftime("%a %d/%m/%y %H:%M")
=> "Wed 03/03/10 11:33"