我想显示以小时、分钟和秒为单位的时间长度,其中某些时间长度大于 24 小时。目前我正在尝试这个:
$timeLength = new DateTime();
$timeLength->setTime(25, 30);
echo $timeLength->format('H:m:i'); // 01:30:00
我希望它显示25:30:00
.
我最好是寻找面向对象的解决方案。
谢谢:)
由于您已经拥有以秒为单位的长度,因此您可以计算它:
function timeLength($sec)
{
$s=$sec % 60;
$m=(($sec-$s) / 60) % 60;
$h=floor($sec / 3600);
return $h.":".substr("0".$m,-2).":".substr("0".$s,-2);
}
echo timeLength(6534293); //outputs "1815:04:53"
如果你真的想使用DateTime
对象,这里有一个(作弊)解决方案:
function dtLength($sec)
{
$t=new DateTime("@".$sec);
$r=new DateTime("@0");
$i=$t->diff($r);
$h=intval($i->format("%a"))*24+intval($i->format("%H"));
return $h.":".$i->format("%I:%S");
}
echo dtLength(6534293); //outputs "1815:04:53" too
如果你需要它OO并且不介意创建自己的类,你可以尝试
class DTInterval
{
private $sec=0;
function __construct($s){$this->sec=$sec;}
function formet($format)
{
/*$h=...,$m=...,$s=...*/
$rst=str_replace("H",$h,$format);/*etc.etc.*/
return $rst;
}
}
DateTime
处理一天中的时间,而不是时间间隔。由于没有25点钟,所以使用起来是错误的。不过,有DateInterval
,它处理日期间隔。使用它或进行一些手动计算。即使有DateInterval
,您也必须进行一些计算,因为它会将间隔分解为几天和几小时。最直接的做法是根据您已经拥有的秒数计算您需要的内容。