[英]PHP - Convert integer number of seconds to ISO8601 format
因此,基本上我想用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;
}
谢谢
这似乎是一个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
您可能会注意到,由于实际月份的大小并不相同,因此我不确定是否确定几个月的持续时间。 我只是根据减少的天数计算得出的,因此,如果持续时间较长,您仍然只会看到高端的天数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.