您可能想要定义一个分辨率,例如一分钟、三分钟或 15 秒或一天半或其他什么。随机性应该应用于整个周期,我在这里选择了一分钟作为示例(您的周期中有 132480 分钟)。
$start = new Datetime('1st October 2012');
$end = new Datetime('1st Jan 2013');
$interval = new DateInterval('PT1M'); // Resolution: 1 Minute
$period = new DatePeriod($start, $interval, $end);
$random = new RandomIterator($period);
list($result) = iterator_to_array($random, false) ? : [null];
这例如给出:
class DateTime#7 (3) {
public $date =>
string(19) "2012-10-16 02:06:00"
public $timezone_type =>
int(3)
public $timezone =>
string(13) "Europe/Berlin"
}
您可以find the RandomIterator here。没有它,它会花费更长的时间(与上面的示例相比,迭代次数约为 1.5):
$count = iterator_count($period);
$random = rand(1, $count);
$limited = new LimitIterator(new IteratorIterator($period), $random - 1, 1);
$limited->rewind();
$result = $limited->current();
我也尝试了几秒钟,但这需要很长时间。您可能希望首先找到一个随机的日期(92 天),然后在其中找到一些随机时间。
此外,我还进行了一些测试,只要您使用秒等常见分辨率,我就找不到使用 DatePeriod 的任何好处:
$start = new Datetime('1st October 2012');
$end = new Datetime('1st Jan 2013');
$random = new DateTime('@' . mt_rand($start->getTimestamp(), $end->getTimestamp()));
或分钟:
/**
* @param DateTime $start
* @param DateTime $end
* @param int|DateInterval $resolution in Seconds or as DateInterval
* @return DateTime
*/
$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);
};
$random = $randomTime($start, $end, 60);