I am using the below method to calculate when the next time in a schedule of times is.
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 is an array, like this:
$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 simply converts, for example, 0 to ‘sunday’.
In order to write unit tests, I need to spoof the time that now() is at, or pass it into the method and use it.
The question is, how can I use that with DateTime?
i.e. DateTime('next wednesday') needs to be told what time ‘now’ is, in order to figure out ‘next wednesday’ in a predictable way, so that it can be unit tested.
The __construct function has an optional param:
An example:
Edit: You can use strtotime to generate a timestamp, then use date to generate the string to pass to the new object: