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回答的一个小扩展,带有可选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
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'参数,更改可用日期的范围.
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)
对于最新版本的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)
Run Code Online (Sandbox Code Playgroud)
随意添加to_date,to_datetime等以转换为您喜欢的课程
在Rails 5.0.3和Ruby 2.3.3上进行了测试,但显然可以在Ruby 1.9+和Rails 3+中使用
| 归档时间: |
|
| 查看次数: |
20325 次 |
| 最近记录: |