Ryan
Ryan

Reputation: 57

PHP Comparing two dates but Hours not functioning correctly

I'm having an issue with my code not displaying the correct difference between dates. The Days Minutes and Seconds all work correctly but the Hours seem to be displayed the subtracted amount and not the remainder if that makes sense at all.

For example, using these dates 2171167 = 2013-05-18 00:00:00 - 2013-04-22 20:53:53

I receive the following output 25 days 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);

If you could please tell me why the second "Hours" variable i have commented out is not working i would very much appreciate it.

Upvotes: 1

Views: 131

Answers (3)

soundari
soundari

Reputation: 35

Just change the hours syntax.

<?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);
?>

Upvotes: 0

BlitZ
BlitZ

Reputation: 12168

<?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');
?>

Shows:

00-0-25 03:6:7

To split into variables:

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

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

Shows:

string(2) "00"
string(1) "0"
string(2) "25"
string(2) "03"
string(1) "6"
string(1) "7"

Upvotes: 3

liyakat
liyakat

Reputation: 11853

you are using wrong first date use below code to your actual answer

$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);

:OUTPUT:

dif -> 26 03:06:07

day -> 26
Hours -> 03
Minutes -> 06
Seconds -> 07

Upvotes: 0

Related Questions