How to generate a random time from an H:i:s formatted timestamp with PHP.
For this example 02:38:55 will be used which represents 2 hours, 38 minutes and 55 seconds. The randomTimeFormatted()function will choose a random formated time in-between 00:00:00 and 02:38:55
Function:
function randomTimeFormatted(string $max_time): string
{
$t = explode(':', $max_time);
return sprintf("%02d:%02d:%02d", rand(0, $t[0]), rand(0, $t[1]), rand(0, $t[2]));
}Example call:
echo randomTimeFormatted('02:38:55');An example return would be 01:24:33, nothing greater than 02:38:55 will be returned.
The simple function turns the timestamp into an array for the hours, minutes and seconds. These are then used in a rand() call with the max value being from the timestamp. It is then all returned through sprintf() to format.