1

我的代码没有显示正确的日期差异时遇到问题。Days Minutes 和 Seconds 都可以正常工作,但 Hours 似乎显示的是减去的数量,而不是剩余部分,如果这完全有意义的话。

例如,使用这些日期 2171167 = 2013-05-18 00:00:00 - 2013-04-22 20:53:53

我在 25 天 19:06:07 收到以下输出

$date_one = date('Y-m-d H:i:s');
$date_two = date('Y-m-d H:i:s', mktime(0, 0, 0, 5, 18, 2013));
$Difference = abs(strtotime($date_two) - strtotime($date_one));

$Days = date("d", $Difference);
//$Hours = date("H", $Difference); Why does this NOT WORK???
$Minutes = date("i", $Difference);
$Seconds = date("s", $Difference);

如果您能告诉我为什么我注释掉的第二个“小时”变量不起作用,我将非常感激。

4

3 回答 3

3
<?php
header('Content-Type: text/plain');

$date1 = DateTime::createFromFormat('Y-m-d H:i:s', '2013-05-18 00:00:00');
$date2 = DateTime::createFromFormat('Y-m-d H:i:s', '2013-04-22 20:53:53');

$result = $date1->diff($date2);

echo $result->format('%Y-%m-%d %H:%i:%s');
?>

显示:

00-0-25 03:6:7

拆分成变量:

list($year, $month, $day, $hour, $minute, $second) = explode('-', $result->format('%Y-%m-%d-%H-%i-%s'));

var_dump($year, $month, $day, $hour, $minute, $second);

显示:

string(2) "00"
string(1) "0"
string(2) "25"
string(2) "03"
string(1) "6"
string(1) "7"
于 2013-04-23T04:11:00.750 回答
0

只需更改小时语法。

<?php
    $date_one = date('Y-m-d H:i:s');
    $date_two = date('Y-m-d H:i:s', mktime(0, 0, 0, 5, 18, 2013));
    $Difference = round(strtotime($date_two) - strtotime($date_one));

    $Days = date("d", $Difference);
    $Hours = date("H", $Difference);
    echo $Hours = $Difference / 60;
    $Minutes = date("i", $Difference);
    $Seconds = date("s", $Difference);
?>
于 2013-04-23T04:14:54.263 回答
0

您使用错误的第一次约会使用下面的代码到您的实际答案

$date_one = "2013-04-22 20:53:53"; //date('Y-m-d H:i:s');
$date_two = date('Y-m-d H:i:s', mktime(0, 0, 0, 5, 18, 2013));
$Difference = abs(strtotime($date_two) - strtotime($date_one));

echo "<br> dif ->".date('d H:i:s',$Difference);

echo "<br> day -> ".$Days = date("d", $Difference);
echo "<br> Hours -> ".$Hours = date("H", $Difference); 
echo "<br> Minutes -> ".$Minutes = date("i", $Difference);
echo "<br> Seconds -> ".$Seconds = date("s", $Difference);

:输出:

差异 -> 26 03:06:07

day -> 26
Hours -> 03
Minutes -> 06
Seconds -> 07
于 2013-04-23T04:17:01.943 回答