
Question:
I have a PHP script that collects a timestamp in a database in the HH:MM:SS format. I then have a PHP page that is refreshed every second via AJAX, the goal of which is to produce a script that pulls PHP data every second so I can do things like display a countdown timer. I am trying to display the difference in two times in this format: HH:MM:SS. IE:
$currentstampedtime = date("H:i:s", strtotime("now"));
Produces:
19:29:34
(and counts up with my ajax script correctly, appears as a clock.
$gametimestamp = date("H:i:s", strtotime($gametime));
Produces:
19:19:12
By pulling the timestamp from my DB, stored in $gametime.
What I am trying to do is get the difference between these two echo'ed out in real time like a countdown timer, assuming the ajax refreshes the page every second like it appears to be doing.
$difference = ($currentstampedtime - $gametimestamp);
Does nothing. When I echo the var,
echo $difference;
I get
1
Nothing I have tried is working. Please help. Thanks in advance.
Answer1:You could use php <a href="http://php.net/manual/en/class.datetime.php" rel="nofollow">DateTime
</a> object to create your current time and target time. Then, use the <a href="http://php.net/manual/en/datetime.diff.php" rel="nofollow">diff()
</a> function of the DateTime object to get the difference and format it as "00:00:00".
i.e. :
$now = new DateTime();
$target = DateTime::createFromFormat('H:i:s', "01:30:00");
$difference = $now->diff($target);
echo $difference->format("%H:%I:%S");
Output :
<blockquote>00:57:48
</blockquote>Hope it helps.
Answer2:Here is your answer:
<?php
$difference = time()-strtotime($gametime);
// You can retrieve the difference as time
echo $currentstampedtime = date("H:i:s", $difference);
?>
<strong>UPDATE</strong>
Another solution
<?php
function get_time_difference($time1, $time2) {
$time1 = strtotime("1980-01-01 $time1");
$time2 = strtotime("1980-01-01 $time2");
if ($time2 < $time1) {
$time2 += 86400;
}
return date("H:i:s", strtotime("1980-01-01 00:00:00") + ($time2 - $time1));
}
echo get_time_difference("10:25:30", "22:40:59"); // 12:15:29
?>