1

我试图获得两天之间的时差。但是对于某些日期/时间,我得到了错误的答案

这是我的代码:

/****************************************
$start_date = new DateTime('23:58:40'); *These two still give 
$end_date = new DateTime('00:00:00');   *a wrong answer
*****************************************/

$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');

$dd = date_diff($end_date, $start_date);

//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4 
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
4

2 回答 2

5

遮阳篷是正确的。你提供两次。如果没有日期,就无法知道最后一个日期实际上是第二天。仅仅因为您将变量命名为“end_date”并不意味着 PHP 知道您的意思。

也许您应该在请求中也包括日期,例如

$start_date = new DateTime('2012-12-07 23:58:40');
$end_date = new DateTime('2012-12-08 00:11:36');

如果您真的想使用时间:

function differenceInTimes($start, $end) {
    if (strtotime($start)>strtotime($end)) {
        //start date is later then end date
        //end date is next day
        $s = new DateTime('2000-01-01 '.$start);
        $e = new DateTime('2000-01-02 '.$end);
    } else {
        //start date is earlier then end date
        //same day
        $s = new DateTime('2000-01-01 '.$start);
        $e = new DateTime('2000-01-01 '.$end);
    }

    return date_diff($s, $e);
}

$start_date = '23:58:40';
$end_date = '00:11:36';
$dd = differenceInTimes($start_date, $end_date);
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";

//Hours = 0, Minutes = 12, Seconds = 56 
于 2012-12-07T14:12:45.307 回答
1

将参数交换为 date_diff

$dd = date_diff($start_date, $end_date);

编辑

在实际测试了这个理论之后,它被证明是完全没用的,给出了相同的答案。

于 2012-12-07T14:10:29.583 回答