如何在Ruby中生成随机日期? [英] How to generate a random date in Ruby?
本文介绍了如何在Ruby中生成随机日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
日期
字段:code> class CreateJobs< ActiveRecord :: Migration
def self.up
create_table:jobs do | t |
t.datejob_date,:null =>假
...
t.timestamps
end
end
...
end
我想用随机日期值预填充我的数据库。
最简单的生成方式是什么一个随机日期?
解决方案
这是Chris的回答稍微扩展,可选的从$参数:
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
I have a model in my Rails 3 application which has a date
field:
class CreateJobs < ActiveRecord::Migration
def self.up
create_table :jobs do |t|
t.date "job_date", :null => false
...
t.timestamps
end
end
...
end
I would like to prepopulate my database with random date values.
What is the easiest way to generate a random date ?
解决方案
Here's a slight expansion on Chris' answer, with optional from
and to
parameters:
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
这篇关于如何在Ruby中生成随机日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文