Home => PHP Projects => Dates/Times  

Difference Between Dates in P H P

PHP does not provide functions to calculate the difference between two timestamps. Here are some ways to do it. As of this writing, I have only accumulated these from the net, but I have not yet evaluated them.


if( $date2 > $date1 )
   { die( "error: date1 has to be >= date2 in calcDateDiff($date1, $date2)" ); }

 $diff = $date1-$date2;
 $seconds = 0;
 $hours   = 0;
 $minutes = 0;

 if($diff % 86400 <= 0)  //there are 86,400 seconds in a day
    {$days = $diff / 86400;}

 if($diff % 86400 > 0)
   {   $rest = ($diff % 86400);
       $days = ($diff - $rest) / 86400;
       if( $rest % 3600 > 0 )
       {   $rest1 = ($rest % 3600);
           $hours = ($rest - $rest1) / 3600;
           if( $rest1 % 60 > 0 )
           {   $rest2 = ($rest1 % 60);
               $minutes = ($rest1 - $rest2) / 60;
               $seconds = $rest2;
           }else
               $minutes = $rest1 / 60;
       }else
           $hours = $rest / 3600;}

$month1 = date('n',$timestamp1);
$month2 = date('n',$timestamp2);
$diff = $month2-$month1;

echo(($diff > 0 ? $diff-1 : $diff+1));

First date: 920264400 Second date: 974240831
$differecne = $first - $second;
echo $difference;
Returns: Difference: 53976431

$diffday = $difference/86400; echo "$diffday (days)";
Returns this: Difference: 624.73377314815 (days)

How can I further format this figure to display like: Difference: 624 days, X hours, X minutes, and X seconds

$string_difference = date("H:m:s",mktime(0,0,$diff,0,0,0)) // I think that'll work.

$filemod = filemtime( 'headlines.txt' );
$now = time();
$seconds = $now - $filemod;
/****************************
Make Minutes
****************************/
$minutes = floor( $seconds / ( int )60 );
/****************************
Get Left Over Seconds
****************************/
$left = $minutes * ( int )60;
$a_seconds = $seconds - $left;
/****************************
Output Message
****************************/
echo( 'File last modifed ' . $minutes . ' minute(s) and ' . $a_seconds . ' second(s) ago.' );

 /* return the difference in days between two PHP timestamps   */
    $var_days = ($ts_1 - $ts_2) / 86400; /// 60 / 60 / 24;


 Viewed 19065 times since July 17,2007 (63 per day over 303.1 days) Home => PHP Projects  
Page: www.michaelhorowitz.com Last Updated: May 24, 2005 5 PM  
Prior to you, the last person to look at this web page did so on Thursday, May 15, 2008 8:18:55 AM
Current time on the server is Thursday, May 15, 2008 8:19:19 AM
There have been 99318 page views of these PHP pages since February 10, 2004 for an average of 64 per day over 1,555.5 days
The last 5 people to view this web site were from these IP addresses:
38.103.63.17no name found
66.249.65.71crawl-66-249-65-71.googlebot.com
59.96.24.52no name found
61.246.177.137egress-del1.globallogic.com
67.195.37.107llf320021.crawl.yahoo.net