Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create random DateTime in Rails

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) 
like image 517
JackCA Avatar asked Mar 09 '10 16:03

JackCA


2 Answers

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 

Update – Rails 4.1+

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 
like image 107
Marc O'Morain Avatar answered Sep 21 '22 06:09

Marc O'Morain


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 
like image 35
Harish Shetty Avatar answered Sep 22 '22 06:09

Harish Shetty