在PHP中获取日期/时间差异

时间:2012-12-07 14:08:38

标签: php date time

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

这是我的代码:

/****************************************
$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";

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分:1)

将参数交换为date_diff

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

修改

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