Categories: 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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago