Best way to create random DateTime in Rails

前端 未结 12 2001
粉色の甜心
粉色の甜心 2020-12-22 23:49

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::Lo         


        
12条回答
  •  天命终不由人
    2020-12-23 00:33

    As I already mentioned in another question I think the following code-snippet is more consisent regarding the data-types of the parameters and of the value to be returned. Stackoverflow: How to generate a random date in Ruby?

    Anyway this uses the rand() method's internal logic what is the random Date or random Time within a span. Maybe someone has a more efficient way to set the default-parameter to (Time.now.to_date) of the method random_date, so it doesn't need this typecasting.

    def random_time from = Time.at(0.0), to = Time.now
      rand(from..to)
    end
    
    # works quite similar to date :)
    def random_date from = Date.new(1970), to = Time.now.to_date
      rand(from..to)
    end
    

    Edit: this code won't work before ruby v1.9.3

提交回复
热议问题