Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 596
Hermine D. Avatar asked Apr 21 '10 14:04

Hermine D.


People also ask

How do I generate a random time between ranges in Excel?

you want to generate random time between two given times, such as generate time from 6 o'clock to 9 o'clock, you can use below formula. Type this formula: =TEXT(RAND()*(8:45-7)/24+6/24,"HH:MM:SS") into a blank cell, and drag the fill handle over to the range that you want to insert the time.


2 Answers

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

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

like image 180
Evgeny Shadchnev Avatar answered Sep 21 '22 02:09

Evgeny Shadchnev


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)) 
like image 45
Jack Chu Avatar answered Sep 22 '22 02:09

Jack Chu