Reputation: 309
I am trying to work out how to return a random time between 2 time ranges. For example, get a random time between 15:00:00 and 22:00:00
So far, I have - but don't know how to limit it
select sec_to_time(floor(15 + (rand() * 86401)))
Any help would be much appreciated!
Upvotes: 5
Views: 5366
Reputation: 2399
Try this way
select FROM_UNIXTIME(UNIX_TIMESTAMP('<starting_date_in_date_format>') + FLOOR(0 + (RAND() * UNIX_TIMESTAMP('<ending_date_in_date_format>'))) from dual;
Upvotes: 1
Reputation: 3807
Logic is simple,
Following is example for getting Random Hour,
select Round((FLOOR(RAND() * (TIME_TO_SEC('15:00:00') - TIME_TO_SEC('22:00:00') + 1)) + TIME_TO_SEC('22:00:00')) / 3600,0)
EDIT : Fiddle
For reference see this link
Upvotes: 1
Reputation: 51908
SELECT SEC_TO_TIME(
FLOOR(
TIME_TO_SEC('15:00:00') + RAND() * (
TIME_TO_SEC(TIMEDIFF('22:00:00', '15:00:00'))
)
)
);
Calculate in seconds. Then add a random number that is in the range of seconds between 15:00:00
and 22:00:00
to 15:00:00
. Then convert the seconds back to a time value.
Upvotes: 11