How to generate a random date and time between two dates?
Don't overlook the 'date AND TIME' part though.
Time.at((date2.to_f - date1.to_f)*rand + date1.to_f)
You'll get a time object that is between two given datetimes.
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))
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)
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()
.
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.
If you know the midpoint and the offset range on either side of the midpoint you can use my ish gem: https://github.com/spilliton/ish
mid_date.ish(:offset => 60.days)
Time.at(rand(Time.parse('some date').to_i..Time.now.to_i))
Calculate the difference in for example minutes between the two dates, generate a random number between 0 and that number, and add that number of minutes to the first date.
Simplest way
rand(DateTime.now..3.days.from_now.to_datetime)
精彩评论