Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random date in Ruby?

I have a model in my Rails 3 application which has a date field:

class CreateJobs < ActiveRecord::Migration
  def self.up
    create_table :jobs do |t|
      t.date "job_date", :null => false
      ...
      t.timestamps
    end
  end
  ...
end

I would like to prepopulate my database with random date values.

What is the easiest way to generate a random date ?

like image 597
Misha Moroshko Avatar asked Feb 04 '11 03:02

Misha Moroshko


3 Answers

Here's a slight expansion on Chris' answer, with optional from and to parameters:

def time_rand from = 0.0, to = Time.now
  Time.at(from + rand * (to.to_f - from.to_f))
end

> time_rand
 => 1977-11-02 04:42:02 0100 
> time_rand Time.local(2010, 1, 1)
 => 2010-07-17 00:22:42 0200 
> time_rand Time.local(2010, 1, 1), Time.local(2010, 7, 1)
 => 2010-06-28 06:44:27 0200 
like image 123
Mladen Jablanović Avatar answered Nov 03 '22 10:11

Mladen Jablanović


Generate a random time between epoch, the beginning of 1970, and now:

Time.at(rand * Time.now.to_i)
like image 39
Chris Heald Avatar answered Nov 03 '22 11:11

Chris Heald


Keeping simple..

Date.today-rand(10000) #for previous dates

Date.today+rand(10000) #for future dates

PS. Increasing/Decreasing the '10000' parameter, changes the range of dates available.

like image 23
iGallina Avatar answered Nov 03 '22 11:11

iGallina