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
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.
A bit of test code to drive the function around the block a couple times:
Output from the test code looks similar to this:
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.