我的 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
我想用随机日期值预填充我的数据库。
生成随机日期的最简单方法是什么?
这是对 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
在纪元、1970 年初和现在之间生成一个随机时间:
Time.at(rand * Time.now.to_i)
保持简单..
Date.today-rand(10000) #for previous dates
Date.today+rand(10000) #for future dates
附言。增加/减少“10000”参数,更改可用日期范围。
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)
对于最新版本的 Ruby/Rails,您可以在
rand
范围内使用 Time
❤️ !!
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+ 获得
对我来说最漂亮的解决方案是:
rand(1.year.ago..50.weeks.from_now).to_date
以下在 Ruby(无 Rails)中返回过去 3 周内的随机日期时间。
DateTime.now - (rand * 21)
这里还有一个(在我看来)改进版的 Mladen 代码片段。幸运的是,Ruby 的 rand() 函数也可以处理时间对象。关于包含 Rails 时定义的日期对象,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
编辑:此代码在 ruby v1.9.3 之前不起作用
这是我在过去 30 天内生成随机日期的一个班轮(例如):
Time.now - (0..30).to_a.sample.days - (0..24).to_a.sample.hours
非常适合我的 lorem ipsum。显然分秒是固定的。
由于您使用的是 Rails,因此可以安装
faker
gem 并使用 Faker::Date 模块。
例如以下生成 2018 年的随机日期:
Faker::Date.between(Date.parse('01/01/2018'), Date.parse('31/12/2018'))
Mladen的回答,单看有点难懂。这是我对此的看法。
def time_rand from=0, to= Time.now
Time.at(rand(from.to_i..to.to_i))
end
给定 2 个日期,它将返回给定日期之间的随机日期:
Time.at(rand(start_date.to_time..end_date.to_time)).to_date
# => Mon, 29 Apr 2019