在Ruby/Rails中生成随机DateTime的最佳方法是什么?试图创建一个漂亮的seeds.rb文件.要像这样使用它:
Foo.create(name: Faker::Lorem.words, description: Faker::Lorem.sentence, start_date: Random.date)
Run Code Online (Sandbox Code Playgroud)
Mar*_*ain 124
以下是过去10年中创建日期的方法:
rand(10.years).ago
Run Code Online (Sandbox Code Playgroud)
您还可以在将来获得日期:
rand(10.years).from_now
Run Code Online (Sandbox Code Playgroud)
当你调用时.ago
,Rails 4.1已经弃用了Numeric => seconds的隐式转换,上面的代码依赖于它.有关此内容的更多信息,请参阅Rails PR#12389.要避免Rails 4.1中的弃用警告,您需要显式转换为秒,如下所示:
rand(10.years).seconds.ago
Run Code Online (Sandbox Code Playgroud)
Har*_*tty 34
以下是用于生成范围内的随机整数,金额,时间/日期时间的一组方法.
def rand_int(from, to)
rand_in_range(from, to).to_i
end
def rand_price(from, to)
rand_in_range(from, to).round(2)
end
def rand_time(from, to=Time.now)
Time.at(rand_in_range(from.to_f, to.to_f))
end
def rand_in_range(from, to)
rand * (to - from) + from
end
Run Code Online (Sandbox Code Playgroud)
现在您可以拨打以下电话.
rand_int(60, 75)
# => 61
rand_price(10, 100)
# => 43.84
rand_time(2.days.ago)
# => Mon Mar 08 21:11:56 -0800 2010
Run Code Online (Sandbox Code Playgroud)
shi*_*ara 17
我更喜欢用 (1..500).to_a.rand.days.ago
luc*_*cas 12
你正在使用Faker; 为什么不使用提供的方法之一Faker::Date
?
# Random date between dates
Faker::Date.between(2.days.ago, Date.today) #=> "Wed, 24 Sep 2014"
# Random date between dates except for certain date
Faker::Date.between_except(1.year.ago, 1.year.from_now, Date.today) #=> "Wed, 24 Sep 2014"
# Random date in the future (up to maximum of N days)
Faker::Date.forward(23) # => "Fri, 03 Oct 2014"
# Random date in the past (up to maximum of N days)
Faker::Date.backward(14) #=> "Fri, 19 Sep 2014"
# Random birthday date (maximum age between 18 and 65)
Faker::Date.birthday(18, 65) #=> "Mar, 28 Mar 1986"
Run Code Online (Sandbox Code Playgroud)
目前的Faker版本:1.9.1
归档时间: |
|
查看次数: |
20630 次 |
最近记录: |