0

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"

3
Contributors
8
Replies
14
Views
3 Years
Discussion Span
Last Post by pritaeas
0

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

What if you leave out the assignment?

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

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.

0

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

0

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');
0

if ($resolution instanceof DateInterval)

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.