Skip to content

Instantly share code, notes, and snippets.

@jgornick
Last active September 3, 2015 22:25
Show Gist options
  • Save jgornick/220610 to your computer and use it in GitHub Desktop.
Save jgornick/220610 to your computer and use it in GitHub Desktop.
PHP: Format Duration
var duration = 3600;
duration = parseInt(Math.abs(duration));
duration =
String('00' + parseInt(duration / 3600)).slice(-2) + ':' +
String('00' + parseInt((duration / 60) % 60)).slice(-2) + ':' +
String('00' + parseInt(duration % 60)).slice(-2);
<?php
// Set our duration in seconds
$duration = 3600;
$isNegative = $duration < 0;
$duration = abs($duration);
$duration =
str_pad($duration / 3600, 2, '0', STR_PAD_LEFT) . ':' .
str_pad(($duration / 60) % 60, 2, '0', STR_PAD_LEFT) . ':' .
str_pad($duration % 60, 2, '0', STR_PAD_LEFT);
$duration = ($isNegative ? '-' : '') . $duration;
echo $duration;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment