All posts

Rails random date generator

 rails

To generate random dates in Rails you can use the DateTime object and a random value to subtract from it. The following code byte will produce a random date in the last 4 weeks:

DateTime.now - (rand * 28)

So then to generate a random date within the last year you can use:

DateTime.now - (rand * 365)

Further reading: