如何在Ruby中生成随机日期?
我的Rails 3应用程序中有一个模型,它有一个date
字段:
class CreateJobs false ... t.timestamps end end ... end
我想用随机日期值预填充我的数据库。
生成随机日期的最简单方法是什么?
这是Chris回答的一个小扩展,带有可选的from
和to
参数:
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
试试这个:
Time.at(rand * Time.now.to_i)
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)
保持简单..
Date.today-rand(10000) #for previous dates Date.today+rand(10000) #for future dates
PS。 增加/减少’10000’参数,更改可用日期的范围。
这里还有一个(在我看来)改进版Mladen的代码片段。 幸运的是Ruby的rand()函数也可以处理Time-Objects。 关于在包含Rails时定义Date-Object,rand()方法被覆盖,因此它也可以处理Date-Objects。 例如:
# 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
编辑:此代码在ruby v1.9.3之前不起作用
这是我在过去30天内生成随机日期的一个class轮(例如):
Time.now - (0..30).to_a.sample.days - (0..24).to_a.sample.hours
适合我的lorem ipsum。 显然会修复几分钟和几秒钟。
对于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_date
, to_datetime
等转换为您喜欢的类
在Rails 5.0.3和Ruby 2.3.3上测试过,但显然可以从Ruby 1.9+和Rails 3+获得
以下内容在Ruby(sans Rails)中返回过去3周内的随机日期时间。
DateTime.now - (rand * 21)
从一个单一的外观来看,Mladen的答案有点难以理解。 这是我对此的看法。
def time_rand from=0, to= Time.now Time.at(rand(from.to_i..to.to_i)) end