所以基本上我有一个我希望用ISO8601格式表示的秒数值。
例如:
90秒将表示为T1M30S
到目前为止,我已完成以下工作:
$length = 90;
$interval = DateInterval::createFromDateString($length . ' seconds');
echo($interval->format('TH%hM%iS%s'));
这个输出是:
TH0M0S90
结束构建此功能,似乎生成了我需要的值(但是限制为不到一天的持续时间:
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;
}
由于
答案 0 :(得分:3)
这似乎是ISO8601持续时间字符串生成器。根据持续时间范围以及处理零秒间隔,它有一堆丑陋的垃圾来捕捉P与T的关系。
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";
}
一些测试代码,用于驱动块周围的功能几次:
$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";
}
测试代码的输出类似于:
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
您可能会注意到,由于实际月数不是完全相同,因此我不确定几个月的持续时间。我只计算了几天的时间,所以如果你有很长的持续时间,你仍然只会看到高端的日子。