PDA

View Full Version : Calculate difference between two dates into hours

levani
09-10-2009, 09:43 PM
How can I calculate difference between the current date and another date, got from database, into hours using php?

I found this example

<?php
\$century = mktime(12, 0, 0, 1, 1, 2001);
\$today = time();
\$difference = \$today - \$century;
echo 'This century started ';
echo floor(\$difference / 84600);
\$difference -= 84600 * floor(\$difference / 84600);
echo ' days, ';
echo floor(\$difference / 3600);
\$difference -= 3600 * floor(\$difference / 3600);
echo ' hours, ';
echo floor(\$difference / 60);
\$difference -= 60 * floor(\$difference / 60);
echo " minutes, and \$difference seconds ago.";
?>

But my first date ( \$century in this example ) isn't static. How should i modify the code? What date format should I use? Do you happen to have any better code?

angst
09-10-2009, 09:49 PM
try this;

\$d1=mktime(22,0,0,1,1,2007);
\$d2=mktime(0,0,0,1,2,2007);
echo "Hours difference = ".floor((\$d2-\$d1)/3600);

levani
09-10-2009, 10:34 PM
One time should be current!

Zangeel
09-10-2009, 11:12 PM
Yey

\$d1= time(); // Current time
\$d2= time() + 3600; // Blus one hour
echo "Hours difference = ".floor((\$d2-\$d1)/3600); // Equal 1 hour

levani
09-11-2009, 07:35 PM
Sorry, but I still a bit confused. Here is how the date is stored in database:

2009-03-24 21:59:17 (just one example)

How can I convert it as Unix timestamp to compare the current date?

angst
09-11-2009, 07:46 PM
try;

\$d1=strtotime('2009-09-11 09:59:17');
\$d2= time();
echo "Hours difference = ".floor((\$d2-\$d1)/3600);

levani
09-11-2009, 07:56 PM
try;

\$d1=strtotime('2009-09-11 09:59:17');
\$d2= time();
echo "Hours difference = ".floor((\$d2-\$d1)/3600);

Works fine, thank you very much for help!