Formatting Duration (time) in PHP

with php >= 5.3.0 you could do that :

$dt = new DateTime();
$dt->add(new DateInterval('PT200M'));
$interval = $dt->diff(new DateTime());
echo $interval->format('%Hh %Im %Ss');

Output (on my locale) : 02h 40m 00s

source : http://php.net/manual/en/class.dateinterval.php


function getNiceDuration($durationInSeconds) {

  $duration = '';
  $days = floor($durationInSeconds / 86400);
  $durationInSeconds -= $days * 86400;
  $hours = floor($durationInSeconds / 3600);
  $durationInSeconds -= $hours * 3600;
  $minutes = floor($durationInSeconds / 60);
  $seconds = $durationInSeconds - $minutes * 60;

  if($days > 0) {
    $duration .= $days . ' days';
  }
  if($hours > 0) {
    $duration .= ' ' . $hours . ' hours';
  }
  if($minutes > 0) {
    $duration .= ' ' . $minutes . ' minutes';
  }
  if($seconds > 0) {
    $duration .= ' ' . $seconds . ' seconds';
  }
  return $duration;
}

Tags:

Datetime

Php