2011-02-04 76 views
26

我有一個模型在我的Rails 3應用程序具有date場:如何在Ruby中生成隨機數據?

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

我想預填充我的數據庫隨機日期值。

生成隨機數據的最簡單方法是什麼?

+0

你不能只是做Time.now?或者你真的需要使用隨機日期嗎? – corroded 2011-02-04 03:20:18

+1

我真的想要隨機值:) – 2011-02-04 04:35:35

回答

54

這裏有一個關於克里斯的回答略有擴大,可選fromto參數:

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 
40

試試這個:

Time.at(rand * Time.now.to_i) 
+0

這將從時代到現在生成一個隨機的日期 – tothemario 2011-11-08 19:36:20

+0

短而甜,我喜歡它。 – sevenseacat 2012-02-15 11:34:52

3

這裏也是一個以上(在我的oppinion)提高姆拉登的版本代碼片斷。幸運的是,Ruby的rand()函數也可以處理時間對象。關於包含Rails的Date-Object定義,rand()方法被覆蓋,所以它也可以處理日期對象。例如:

# works even with basic ruby 
def random_time from = Time.at(0.0), to = Time.now 
    rand(from..to) 
end 

# works only with rails. syntax is quite similar to time method above :) 
def random_date from = Date.new(1970), to = Time.now.to_date 
    rand(from..to) 
end 

編輯:此代碼不會紅寶石v1.9.3

10

好工作之前,

保持簡單..

Date.today蘭特(10000)對以前

日期

今日+蘭特(10000)未來日期

PS。增加/減少'10000'參數,改變可用日期的範圍。

13
rand(Date.civil(1990, 1, 1)..Date.civil(2050, 12, 31)) 

我最喜歡的方法

def random_date_in_year(year) 
    return rand(Date.civil(year.min, 1, 1)..Date.civil(year.max, 12, 31)) if year.kind_of?(Range) 
    rand(Date.civil(year, 1, 1)..Date.civil(year, 12, 31)) 
end 

然後用像

random_date = random_date_in_year(2000..2020) 
2

這裏是我的一個襯墊,以產生在過去30天隨機日期(例如):

Time.now - (0..30).to_a.sample.days - (0..24).to_a.sample.hours 

適用於我的lorem ip和。顯然分秒會被固定。

0

對於最新版本的Ruby/Rails,您可以在Time範圍內使用rand❤️!

min_date = Time.now - 8.years 
max_date = Time.now - 1.year 
rand(min_date..max_date) 
# => "2009-12-21T15:15:17.162+01:00" (Time) 

隨意添加to_dateto_datetime等轉換到你最喜歡的課

測試on Rails的5.0.3和2.3.3的Ruby,但顯然可以從紅寶石1.9+和Rails 3+

0

Mladen的答案有一點難以理解,只需一個眼神。這是我對此的看法。

def time_rand from=0, to= Time.now 
    Time.at(rand(from.to_i..to.to_i)) 
end 
0

以下內容在Ruby(sans Rails)中返回過去3周的隨機日期 - 時間。

DateTime.now - (rand * 21)