This is another function to calculate the difference between two times and output it in a relative format. This one, however, combines various units. In other words, it will return "3 days, 2 hours, 6 minutes, and 2 seconds ago" instead of "3 days ago."



Please bear in mind that it is intended for times that are very close together. It will not be accurate for calculating dates more than a month apart. This is because one of the units it relies on is "weeks," which do not correspond directly with months. What I'm trying to get across is, the program assumes that a month is precisely 4 weeks long, i.e. 28 days. This also means that a "year" according to this function is 336 days.



<?php

function rel_time ( $from , $to = null )

{

$to = (( $to === null ) ? ( time ()) : ( $to ));

$to = (( is_int ( $to )) ? ( $to ) : ( strtotime ( $to )));

$from = (( is_int ( $from )) ? ( $from ) : ( strtotime ( $from )));



$units = array

(

"year" => 29030400 , "month" => 2419200 , "week" => 604800 , "day" => 86400 , "hour" => 3600 , "minute" => 60 , "second" => 1 );



$diff = abs ( $from - $to );

$suffix = (( $from > $to ) ? ( "from now" ) : ( "ago" ));



foreach( $units as $unit => $mult )

if( $diff >= $mult )

{

$and = (( $mult != 1 ) ? ( "" ) : ( "and " ));

$output .= ", " . $and . intval ( $diff / $mult ). " " . $unit .(( intval ( $diff / $mult ) == 1 ) ? ( "" ) : ( "s" ));

$diff -= intval ( $diff / $mult ) * $mult ;

}

$output .= " " . $suffix ;

$output = substr ( $output , strlen ( ", " ));



return $output ;

}

?>



The function rel_time() accepts two parameters: $from and $to. For best results, provide them as UNIX timestamps (derived from PHP's time() function). They also accept formats supported by strtotime(). $to is an optional argument and defaults to the current time.



The function will calculate the difference between $from and $to. If $from occurs after $to, the function will substitue "ago" with "from now."



Example usage:

<?php

echo rel_time ( "September 2, 2010 4:20 PM" );

?>