Best way to create random DateTime in Rails

前端 未结 12 2020
粉色の甜心
粉色の甜心 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:24

    I haven't tried this myself but you could create a random integer between two dates using the number of seconds since epoch. For example, to get a random date for the last week.

    end = Time.now
    start = (end - 1.week).to_i
    random_date = Time.at(rand(end.to_i - start)) + start
    

    Of course you end up with a Time object instead of a DateTime but I'm sure you can covert from here.

提交回复
热议问题