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.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…