I am trying to edit the following script to generate a unique time between
00:00:01 and 01:30:00

Using the following script.

    $start    = new Datetime('00:00:01');
    $end      = new Datetime('01:30:00');

    $randomTime = function (DateTime $start, DateTime $end, $resolution = 1) {

        if ($resolution instanceof DateInterval) {
            $interval   = $resolution;
            $resolution = ($interval->m * 2.62974e6 + $interval->d) * 86400 + $interval->h * 60 + $interval->s;
        }

        $startValue = floor($start->getTimestamp() / $resolution);
        $endValue   = ceil($end->getTimestamp() / $resolution);
        $random     = mt_rand($startValue, $endValue) * $resolution;

        return new DateTime('@' . $random);
    };

    echo $random = $randomTime($start, $end, 60);

When I run the script I get the follwing error message
"Catchable fatal error: Object of class DateTime could not be converted to string"

Online line 18 when I try to echo out the time generated ?

echo $random = $randomTime($start, $end, 60);

What if you leave out the assignment?

echo $randomTime($start, $end, 60);

The page loads without error, But how would I know what the random time is ?

I'm not sure, but most posts I've read about this notice that using the format() function might work. So you would return a value that is returned by Datetime::format() instead of just Datetime.

That should be returned by your closure and subsequently echoed. Are you sure the closure does what you want?

Yes, When I use

echo $random->format('H:i:s'); 

I get a random time, but not between

    $start    = new Datetime('00:00:01');
    $end      = new Datetime('01:30:00');

if ($resolution instanceof DateInterval)

Assumes you are passing an interval object, yet you are passing an integer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.