PHP DateTime-为';下周三';离开


PHP DateTime - set a start point for things like 'next wednesday' to go off

我使用以下方法来计算时间表中的下一个时间是。

public static function getNextUtcTimestampFromSchedule($schedule, $timezone)
{
    $timestamps = array();
    foreach ($schedule as $day => $times){
        $dt = new 'DateTime('next '.self::getDayString($day), new 'DateTimeZone($timezone));
        foreach ($times as $time){
            list($hour, $min) = explode(':', $time);
            $dt->setTime($hour, $min);
            $timestamps[] = $dt->getTimestamp();
        }
    }
    sort($timestamps);
    return $timestamps[0];
}

$schedule是一个数组,如下所示:

$schedule = array(
    0 => array('11:00', '17:00'), 
    1 => array('10:00', '18:00'),
    2 => array('09:00', '18:00'), 
    3 => array('11:00', '17:00'),
    4 => array('11:00', '16:00'),
    5 => array('15:00', '16:00'),
    6 => array('11:00', '12:00'),
);

例如,getDayString只是将0转换为"sunday"。

为了编写单元测试,我需要伪造now()的时间,或者将其传递到方法中并使用它

问题是,我如何将其用于DateTime?

DateTime('next wednesday')需要被告知"现在"是什么时间,以便以可预测的方式计算出"下周三",以便对其进行单元测试。

__construct函数有一个可选参数:

public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

一个例子:

<?php
try {
    $date = new DateTime('2000-01-01');
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}
echo $date->format('Y-m-d');
?>

编辑:您可以使用strtotime生成时间戳,然后使用date生成要传递给新对象的字符串:

$date = new DateTime(date("Y-m-d", strtotime("next wednesday")));