Login

My PHP Digest

Duration Calculator

23rd Apr 2007

Always useful to show people the duration of something, like in my upcoming project Event Manage Duration from two dates, including the times. This only takes about 6 lines to do.

How to use the function

Use the following code as stated below


<?php

    $s 
mktime(930007151990);

    list(
$year,$month,$day,$hour,$minute,$second) = split('[:-]' ,date('Y-m-d H:i:s'));
    
$e mktime($hour$minute$second$month$day$year);

    echo 
Duration($s$e);

?>

Output example

The output from the how to above, when taken

16 years 40 weeks 6 days 7 hours 44 minutes

Function


<?php

function Duration($s$e){
    
    
/* Find out the seconds between each dates */
    
$timestamp $e $s;
    
    
/* Cleaver Maths! */
    
$years=floor($timestamp/(60*60*24*365));$timestamp%=60*60*24*365;
    
$weeks=floor($timestamp/(60*60*24*7));$timestamp%=60*60*24*7;
    
$days=floor($timestamp/(60*60*24));$timestamp%=60*60*24;
    
$hrs=floor($timestamp/(60*60));$timestamp%=60*60;
    
$mins=floor($timestamp/60);$secs=$timestamp%60;
   
    
/* Display for date, can be modified more to take the S off */
    
if ($years >= 1) { $str.= $years.' years '; }
    if (
$weeks >= 1) { $str.= $weeks.' weeks '; }
    if (
$days >= 1) { $str.=$days.' days '; }
    if (
$hrs >= 1) { $str.=$hrs.' hours '; }
    if (
$mins >= 1) { $str.=$mins.' minutes '; }
   
     return 
$str;
        
}

?>
© 2006 John's PHP Digest. All Rights Reserved