1

I'm looking to create a countdown timer in PHP. When a user clicks a button it saves the current date & time into a database entry, then it should take the difference of that entry with the current date and time and 'doSomething' when the difference is larger than 48 hours.

My issue is with the actual countdown.

I've tried the following but to no avail it only counts the difference of the of both strings and doesn't take the days in account. Not only that but it also appears to show the resulted difference incorrectly:

$d1=strtotime("2012-07-08 11:14:15");
$d2=strtotime("2012-07-09 12:14:15");
$diff = round(abs($d1 - $d2));
$cd = date("H:i:s", $diff);
echo $cd;

Thanks for helping me Yan.kun from StackOverflow! The code submitted below was the solution! In order to display strictly the countdown in hours:minutes:seconds I replaced the printf() code with the following:

$hours = ($result->d*24)+$result->h;
$minutes = $result->i;
$seconds = $result->s;
echo $hours . ":" . $minutes . ":" . $seconds;
Dxx
  • 934
  • 2
  • 11
  • 41

2 Answers2

2

Try this instead:

$d1 = new DateTime("2012-07-08 11:14:15");
$d2 = new DateTime("2012-07-09 12:14:15");
$result = $d1->diff($d2);

printf('difference is %d day(s), %d hour(s), %d minute(s)', $result->d, $result->h, $result->i);

EDIT: And if you have no PHP 5.3 available, you can convert your times into an unix epoch timestamp like described in this answer.

Community
  • 1
  • 1
yan.kun
  • 6,820
  • 2
  • 29
  • 38
  • Fantastic! Thank you. I wanted it to display the entire difference in strictly Hours:Minutes:Seconds and since the countdown will be 2 days at max I replaced printf with the code I added in the OP. – Dxx Nov 20 '12 at 13:45
0

not sure if this is what you want:

$d1=strtotime("2012-11-18 11:14:15");//2 days earlier
$d2=strtotime("2012-11-20 11:14:15");//today
$diff = $d2 - $d1; //difference in seconds.

$hours = $diff/60/60;//translation to minutes then to hours

echo $hours;

if($hours>48){
    echo "Script";
}
aleation
  • 4,796
  • 1
  • 21
  • 35