How to generate a random date and time between two dates?

16,800

Solution 1

Time.at((date2.to_f - date1.to_f)*rand + date1.to_f)

You'll get a time object that is between two given datetimes.

Solution 2

You should be able to generate random date/times within a certain range.

now = Time.now
a_day_ago = now - 60 * 60 * 24

random_time = rand(a_day_ago..now)

# with activesupport required
up_to_a_year_ago = rand(1.year.ago..Time.now)

Your inputs need to be the Time class, or converted into one though.

You could do also do a range of time in epoch time and then use Time#at.

now = Time.now.to_i
minute_ago = (Time.now - 60).to_i
Time.at(rand(minute_ago..now))

Solution 3

Use the rand() method.

require 'time'
t1 = Time.parse("2015-11-16 14:40:34")
t2 = Time.parse("2015-11-20 16:20:23")
puts rand(t1..t2)

Solution 4

Use time.to_i() (see class Time) to convert your dates to integer, randomize between those two values, then reconvert to time and date with Time.at().

Solution 5

I don't know about ruby but why don't you just generate an integer and use it together with a timestamp? Then simply convert the timestamp to your desired format.

Share:
16,800
Hermine D.
Author by

Hermine D.

Updated on June 09, 2022

Comments

  • Hermine D.
    Hermine D. about 2 years

    Don't overlook the 'date AND TIME' part though.

  • rmontgomery429
    rmontgomery429 over 12 years
    This is a great solution however a note may be in order; you will need to convert your date to a time in order to call to_f on it. Date does not have a to_f. i.e. Date.today.to_time
  • vvohra87
    vvohra87 over 12 years
    I need to find a way to give you another +1 - 2nd time this week I've referred to this answer!
  • severin
    severin almost 12 years
    In my opinion, this solution is much nicer than the currently accepted one by Evgeny.
  • severin
    severin almost 12 years
    One small remark, though: 1.year.ago only works when you have activesupport loaded...
  • Jack Chu
    Jack Chu almost 12 years
    Good point @severin. I included code for support with and without activesupport loaded. Also added an example for epoch time ranges.
  • nroose
    nroose almost 11 years
    For me, now at least, in 1.9.3, I can do date1 + (date2 - date1) * rand, and it comes out as a time.
  • Artur INTECH
    Artur INTECH about 6 years
    Came to the same solution, the most readable option among other answers, IMHO
  • XtraSimplicity
    XtraSimplicity about 5 years
    Or even simpler: rand((DateTime.now - 3.months)..DateTime.now)