简体   繁体   中英

How I can get one random DateTime from DatePeriod?

I'm creating one DatePeriod with this code:

$beginDate=new DateTime();
$beginDate->setTime(0,30);
$mPeriod = new DatePeriod(
    $beginDate, 
    DateInterval::createFromDateString('+1 minutes'), 
    90
);

I can print each object into this period, for example:

foreach ($mPeriod as $period) {
    echo $period->format('Y-m-d H:i') . PHP_EOL;
}

But I don't know how I can take only one of the DateTime objects into this period. I want use one of these values randomly.

The question was answered with a comment and is therefore always found when searching for unanswered questions.

Variant 2 from Kevin's comment as a code:

$beginDate=new DateTime();
$beginDate->setTime(0,30);
$mPeriod = new DatePeriod(
    $beginDate, 
    DateInterval::createFromDateString('+1 minutes'), 
    90
);

$rndKey = random_int(0,90);
foreach($mPeriod as $key => $period){
  if($key == $rndKey) {
    echo $period->format('Y-m-d H:i');
  }
}

However, if only a random time between 00:30 and 02:00 is required, it is faster and easier without DateInterval:

$rndTime = date_create('today 0:30')
  ->modify(random_int(0,90).' Minutes')
;
echo $rndTime->format('Y-m-d H:i');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM