PHP - Convert integer number of seconds to ISO8601 format

2.2k views Asked by At

So basically I have a value of number of seconds which I want to represent in ISO8601 format.

For example:

90 seconds would be represented as T1M30S

So far I have done the following:

$length = 90;
$interval = DateInterval::createFromDateString($length . ' seconds');
echo($interval->format('TH%hM%iS%s'));

The output for this is:

TH0M0S90


Ended up building this function which seems to generate the values I need (it is however limited to a time duration that are less than a day:

public function DurationISO8601(){

        $lengthInSeconds = $this->Length;
        $formattedTime = 'T';

        $units = array(
            'H' => 3600,
            'M' => 60,
            'S' => 1
        );

        foreach($units as $key => $unit){
            if($lengthInSeconds >= $unit){
                $value = floor($lengthInSeconds / $unit);
                $lengthInSeconds -= $value * $unit;
                $formattedTime .= $value . $key;
            }
        }

        return $formattedTime;
    }

Thanks

1

There are 1 answers

1
A Smith On

Here is what appears to be an ISO8601 duration string generator. It has a bunch of ugly junk to catch starting with a P versus a T depending on duration scope as well as handling a zero second interval.

function iso8601_duration($seconds)
{
  $intervals = array('D' => 60*60*24, 'H' => 60*60, 'M' => 60, 'S' => 1);

  $pt = 'P';
  $result = '';
  foreach ($intervals as $tag => $divisor)
  {
    $qty = floor($seconds/$divisor);
    if ( !$qty && $result == '' )
    {
      $pt = 'T';
      continue;
    }

    $seconds -= $qty * $divisor;    
    $result  .= "$qty$tag";
  }
  if ( $result=='' )
    $result='0S';
  return "$pt$result";
}

A bit of test code to drive the function around the block a couple times:

$testranges = array(1, 60*60*24-1, 60*60*24*2, 60*60*24*60);
foreach ($testranges as $endval)
{
  $seconds = mt_rand(0,$endval);
  echo "ISO8601 duration test<br>\n";
  echo "Random seconds: " . $seconds . "s<br>\n";

  $duration = iso8601_duration($seconds);
  echo "Duration: $duration<br>\n";
  echo "<br>\n";
}

Output from the test code looks similar to this:

ISO8601 duration test
Random seconds: 0s
Duration: T0S

ISO8601 duration test
Random seconds: 3064s
Duration: T51M4S

ISO8601 duration test
Random seconds: 19872s
Duration: T5H31M12S

ISO8601 duration test
Random seconds: 4226835s
Duration: P48D22H7M15S

You might note that I'm a little unsure of determining what a duration of months represents since actual months are not all the same size. I've only calculated from days down so if you have a long duration you'll still only see days at the high end.