如何在Ruby中生成随机日期?

Mis*_*hko 36 ruby random ruby-on-rails date ruby-on-rails-3

我在我的Rails 3应用程序中有一个模型,它有一个date字段:

class CreateJobs < ActiveRecord::Migration
  def self.up
    create_table :jobs do |t|
      t.date "job_date", :null => false
      ...
      t.timestamps
    end
  end
  ...
end
Run Code Online (Sandbox Code Playgroud)

我想用随机日期值预填充我的数据库.

生成随机日期的最简单方法是什么?

Mla*_*vić 64

这是Chris回答的一个小扩展,带有可选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 
Run Code Online (Sandbox Code Playgroud)

  • 有用.只是想知道它可以用`Time.at(rand*Time.now.to_f)简化吗? (3认同)
  • 我一直想知道这将成为红宝石核心的一部分!就像`rand(date1..date2)`! (2认同)

Chr*_*ald 44

试试这个:

Time.at(rand * Time.now.to_i)
Run Code Online (Sandbox Code Playgroud)


iGa*_*ina 16

保持简单..

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

Date.today+rand(10000) #for future dates
Run Code Online (Sandbox Code Playgroud)

PS.增加/减少'10000'参数,更改可用日期的范围.

  • 它可以简单地写成`Date.today-rand(10000)`或`Date.today + rand(10000)` (6认同)

idr*_*bst 14

rand(Date.civil(1990, 1, 1)..Date.civil(2050, 12, 31))
Run Code Online (Sandbox Code Playgroud)

我最喜欢的方法

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
Run Code Online (Sandbox Code Playgroud)

然后使用喜欢

random_date = random_date_in_year(2000..2020)
Run Code Online (Sandbox Code Playgroud)


Cyr*_*ris 5

对于最新版本的Ruby / Rails,可以randTime范围?? 上使用?!!

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)
Run Code Online (Sandbox Code Playgroud)

随意添加to_dateto_datetime等以转换为您喜欢的课程

在Rails 5.0.3和Ruby 2.3.3上进行了测试,但显然可以在Ruby 1.9+和Rails 3+中使用


Mar*_*eas 5

对我来说最漂亮的解决方案是:

rand(1.year.ago..50.weeks.from_now).to_date
Run Code Online (Sandbox Code Playgroud)