Best way to create random DateTime in Rails

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

    You can pass Time Range to rand

    rand(10.weeks.ago..1.day.ago)
    

    Output Example:

    => Fri, 10 Jan 2020 10:28:52 WIB +07:00
    
    0 讨论(0)
  • 2020-12-23 00:15

    My 'ish' gem provides a nice way of handling this:

    # plus/minus 5 min of input date
    Time.now.ish
    # override that time range like this
    Time.now.ish(:offset => 1.year)
    

    https://github.com/spilliton/ish

    0 讨论(0)
  • 2020-12-23 00:23

    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
    
    0 讨论(0)
  • 2020-12-23 00:24

    This is what I use:

    # get random DateTime in last 3 weeks
    DateTime.now - (rand * 21)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-23 00:27

    I prefer use (1..500).to_a.rand.days.ago

    0 讨论(0)
提交回复
热议问题