【问题标题】:php compare timesphp比较时间
【发布时间】:2012-08-21 23:48:22
【问题描述】:

下面的 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

【问题讨论】:

    标签: php datetime


    【解决方案1】:

    您正在进行字符串比较,而不是日期比较,这就是它“失败”的原因。

    请改用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')
    );
    

    【讨论】:

    • VB 中的字符串比较不会延续到 PHP
    • @ColeJohnson:你在说什么?抱歉,我不懂VB。
    • 我以为我在使用日期函数来包装时间
    • @ColeJohnson:date() 函数返回一个字符串,而不是整数。 date() 的手册页会告诉你这一点。 ;-)
    • @drrcknlsn - 这里没有争论(虽然我会犹豫说从不)。我只注意到字符串比较本身并没有因为时间格式的一些特殊效果而失败。这是通过比较没有日期的时间引起的。
    猜你喜欢
    • 2011-08-13
    • 2011-09-03
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多