下面的php代码使用strtotime比较当前时间两次:
$timingsfirstTime[0] = date("H:i:s", strtotime(trim($showTimings[0])));
$timingslastTime[2] = date("H:i:s", strtotime(trim($showTimings[2])));
//确认首播节目的开始时间大于频道上次播放的最后时间
$current_time = date("H:i:s",strtotime('now'));
$this->assertTrue(($current_time > $timingsfirstTime[0] && $current_time < $timingslastTime[2]),"current time ".$current_time. " is not greater than current show start time ". $timingsfirstTime[0] . " or current time is not less than current show end time ".$timingslastTime[2]);
但我的断言以某种方式失败并输出:
当前时间00:38:45不大于当前显示开始时间23:50:00或当前时间不小于当前显示结束时间00:50:00
答案 0 :(得分:3)
你正在进行字符串比较,而不是日期比较,这就是它“失败”的原因。
使用DateTime
代替,因为它更容易阅读,代码更少,并且可以原生比较。我还会将你的断言分成两个断言,以便更容易分辨出哪个案例失败了:
$now = new DateTime();
$start = new DateTime($showTimings[0]);
$end = new DateTime($showTimings[2]);
$this->assertTrue(
$now > $start,
'current time ' . $now->format('H:i:s')
. ' is not greater than current show start time '
. $start->format('H:i:s')
);
$this->assertTrue(
$now < $end,
'current time ' . $now->format('H:i:s')
. ' is not less than current show end time '
. $end->format('H:i:s')
);