Version: 1.0
Type: Function
Category: Calendars/Dates
License: GNU General Public License
Description: Calculates elapsed time between two dates in MySQL DATETIME format, with formatting options (units, decimals)for output.
<?php /********************************************************************* * get_elapsed_time.php * * Author: Steve Werby <steve at(@) befriend dot(.) com> * Created: 2001-01-10 17:00 * Revised: 2001-01-10 17:45 * * Purpose: Calculates elapsed time between two dates in MySQL DATETIME format, with formatting options (units, decimals) for output. * * Latest version always available at http://www.befriend.com/. *********************************************************************/ /********************************************************************* * get_mysql_to_epoch() - converts MySQL datetime to epoch time in * seconds. *********************************************************************/ function get_mysql_to_epoch( $date ) { list( $year, $month, $day, $hour, $minute, $second ) = split( '([^0-9])', $date ); return date( 'U', mktime( $hour, $minute, $second, $month, $day, $year ) ); } /********************************************************************* * get_elapsed_time() - difference b/w start and end time in desired * units. *********************************************************************/ function get_elapsed_time( $time_start, $time_end, $units = 'seconds', $decimals = 2 ) { $divider['years'] = ( 60 * 60 * 24 * 365 ); $divider['months'] = ( 60 * 60 * 24 * 365 / 12 ); $divider['weeks'] = ( 60 * 60 * 24 / 7 ); $divider['days'] = ( 60 * 60 * 24 ); $divider['hours'] = ( 60 * 60 ); $divider['minutes'] = ( 60 ); $divider['seconds'] = 1; $elapsed_time = ( ( get_mysql_to_epoch( $time_end ) - get_mysql_to_epoch( $time_start ) ) / $divider[$units] ); $elapsed_time = sprintf( "%0.{$decimals}f", $elapsed_time ); return $elapsed_time; } /********************************************************************* * Usage. *********************************************************************/ $time_in = '2000-06-14 06:30:00'; $time_out = '2000-12-22 13:45:00'; // Full use of function. echo '<br>Days: '; echo get_elapsed_time( $time_in, $time_out, 'days', 3 ); // Use defaults for units and decimal places. echo '<br>Seconds: '; echo get_elapsed_time( $time_in, $time_out ); ?>