在 Rails 中创建随机日期时间的最佳方法 [英] Best way to create random DateTime in Rails

查看:37
本文介绍了在 Rails 中创建随机日期时间的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby/Rails 中生成随机 DateTime 的最佳方法是什么?试图创建一个不错的seeds.rb 文件.打算像这样使用它:

What is the best way to generate a random DateTime in Ruby/Rails? Trying to create a nice seeds.rb file. Going to use it like so:

 Foo.create(name: Faker::Lorem.words, description: Faker::Lorem.sentence, start_date: Random.date)

推荐答案

这里有一组方法来生成一个范围内的随机整数、数量、时间/日期时间.

Here are set of methods for generating a random integer, amount, time/datetime within a range.

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

现在您可以拨打以下电话.

Now you can make the following calls.

rand_int(60, 75)
# => 61

rand_price(10, 100)
# => 43.84

rand_time(2.days.ago)
# => Mon Mar 08 21:11:56 -0800 2010

这篇关于在 Rails 中创建随机日期时间的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆