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 is how to create a date in the last 10 years:
rand(10.years).ago
You can also get a date in the future:
rand(10.years).from_now
Rails 4.1 has deprecated the implicit conversion from Numeric => seconds when you call .ago
, which the above code depends on. See Rails PR #12389 for more information about this. To avoid a deprecation warning in Rails 4.1 you need to do an explicit conversion to seconds, like so:
rand(10.years).seconds.ago
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With