IRsoft - Software and more by Ingmar Runge

PHP: duration_fmt()

A simple function which takes a number of seconds and returns it split into days, hours, etc. and formatted based on a given format string.

<?php
 
/**
 * Does nice formatting in days, hours, minutes and seconds
 * for a given number of seconds.
 * 
 * @param string $format the placeholders %d, %h, %m and %s
 *                       will be replaced with the corresponding values.
 *                       Use lowercase letters/captial letters to do
 *                       with/without leading zeros.
 * @param int $timestamp1 either the total amount of seconds or a
 *                        certain number from which $timstamp2
 *                        will be substracted
 * @param int $timestamp2 the number to substract from $timestamp1 or
 *                        nothing if $timestamp1 already is the number
 *                        of seconds to format
 * 
 * @author mooooz
 * @author KingIR
 * 
 * Examples:
 * echo duration_fmt('%D Days, %H Hours, %H Minutes %H Seconds',
 *                                 time(), time() - 93600);
 * echo duration_fmt('%D Days, %h:%m:%s', 3611);
 **/
function duration_fmt($format, $timestamp1, $timestamp2 = NULL)
{
  // if $timestamp2 is 0, just the value of $timestamp1
  $difference = abs($timestamp1 - (int)$timestamp2);
  
  $placeholders = array(
    array('name' => '%d', 'divisor' => 86400),
    array('name' => '%h', 'divisor' => 3600),
    array('name' => '%m', 'divisor' => 60),
    array('name' => '%s', 'divisor' => 0)
  );
  
  $result = $format;
  
  $pad_func = create_function('$s', 'return str_pad($s, 2, \'0\', STR_PAD_LEFT);');
  
  foreach($placeholders as $ph)
  {
    if(stristr($format, $ph['name']) !== false)
    {
      $tmp = '';
      
      if($ph['divisor'] == 0)
      {
        $tmp = $difference;
      }
      else
      {
        $tmp = floor($difference / $ph['divisor']);
        $difference = $difference - ($tmp * $ph['divisor']);
      }
      
      $result = str_replace(array($ph['name'], strtoupper($ph['name'])),
        array($pad_func((string)$tmp), (string)$tmp), $result);
    }
  }
  
  return $result;
}
 
?>
Last edited by Ingmar on Friday, May 26th 2006 15:56:32 CEST