Best way to create random DateTime in Rails

Here is how to create a date in the last 10 years:

rand(10.years).seconds.ago

You can also get a date in the future:

rand(10.years).seconds.from_now

Older versions of Rails (< 4.1)

Prior to Rails 4.1, there was an implicit conversion from Numeric => seconds when you call .ago. See Rails PR #12389 for more information about this. So this approach is possible:

rand(10.years).ago

rand(10.years).from_now

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)