# Calculating the difference

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hej dudes,

I need to calc the difference between two timestamps / dates ...

For example what i need to calculate:

Date 1: 2007.11.06 - 20:13:04
Date 2: 2007.11.07 - 21:13:04

Difference: 1 day, 1hour

Very simple in php ..

but how do i calculate the difference between the following values:

Date 1: 2007.11.06 - 20:13:04
Date 2: 2007.11.08 - 03:13:04

Does someone have a quick solution for this ?

## Re: Calculating the difference

Julius wrote:

Very simple?

Why is the first simple and the second hard?

Anyway: go to www.php.net and look up: strtotime

Then use the difference in time to calculate the elapsed <whatever unit
suits you>.

Beware of timezone offset stuff. If it is not in the original date,
don't worry.

Regards,
Erwin Moller

## Re: Calculating the difference

First, http://pt.php.net/manual/en/function.strtotime.php . Then
\$later_time - \$earlier_time.

\$date1 = '2005-12-25 00:56:27 GMT' ; // Note the timezone
specification
\$time1 = strtotime(\$date1) ;
\$date2 = '2005-12-27 05:56:27 GMT' ; // Note the timezone
specification
\$time2 = strtotime(\$date2) ;

\$difference = \$time2 - \$time1;

print date('z \d\a\y\s\, H:i:s', \$difference - 3600); // X days,
Hours:Minutes:Seconds

I added - 3600 because it was showing 01:00:00 even when \$difference
was 0. Probably DST thingie.

## Re: Calculating the difference

Kimmo Laine wrote:

Unless next_page.php generates PHP, the script with this include will
only get HTML.

next_page.php

<?php
if (isset(\$_GET['foo'])) {
echo '<?php echo \$_GET[\'foo\']; ?>';
} else {
echo '<?php echo \'Not available\'; ?>';
}

--

## Re: Calculating the difference

Kimmo Laine wrote:

Unless next_page.php generates PHP, the script with this include will
only get HTML.

next_page.php

<?php
if (isset(\$_GET['foo'])) {
echo '<?php echo \$_GET[\'foo\']; ?>';
} else {
echo '<?php echo \'Not available\'; ?>';
}

--

## Re: Calculating the difference

It might work fine but I found out it only goes to 364 days of
distance, so here's a new code, completely fixed for that bug:

[PHP]
<?php
\$date1 = '2005-12-25 00:56:27 GMT' ; // Note the timezone
specification
\$date2 = '2005-12-27 05:56:27 GMT' ; // Note the timezone
specification
\$time_fix = 3600;

\$time1 = strtotime(\$date1);
\$time2 = strtotime(\$date2) ;
\$difference = \$time2 - \$time1;
\$years = date('Y', \$difference) - 1970;

print "\$years years, ";
print date('z \d\a\y\s\, H:i:s', \$difference - \$time_fix); // X days,
Hours:Minutes:Seconds
?>
[/PHP]

I removed the 1970 because that was the default value, so if the
distance is 0 years, then it will show up as 1970 - 1970 which is 0.

Also, in \$time_fix, you can edit the number of seconds to remove from
the difference, so if you don't need to remove 3600 or whatever, you
can edit that easily.