Development

Random time from timestamp string with PHP

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.

Gist link.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago