DateInterval 失败,带有十进制数

问题描述 投票:0回答:1

我有一个 ISO 格式的持续时间,我需要将其转换为秒数。我使用函数

DateInterval
来提取
years, mounths, days, hours, minutes and seconds
并将其转换为秒。但我有一个问题:当 ISO 格式的持续时间仅包含
int
数字(PT2M2S)时,
DateInterval
函数完美工作,但当持续时间包含十进制数字(PT2M2.6S)时,
DataInterval
函数不起作用。

示例:$session_time =

"PT2M2S";
当我使用
DataInterval
时:

`$interval = new DateInterval($session_time);` 
$sessionTimeBySeconde = $interval->y*525600*60 + $interval->m*43800*60 + $interval->h*3600 + $interval->i*60 + $interval->s;

在这种情况下它工作得很好。

现在,如果我有例子:$session_time =

"PT2M2.6S";
如果我像上面一样使用 DataInterval :

`$interval = new DateInterval($session_time);` 
$sessionTimeBySeconde = $interval->y*525600*60 + $interval->m*43800*60 + $interval->h*3600 + $interval->i*60 + $interval->s;

在这种情况下它不起作用..

对于信息,我不对值负责

$session_time
,我只是从另一个系统获取它,我想将其转换为秒。

我能做什么?

php time iso
1个回答
0
投票

今年是2024年!目前这还是一个 PHP 问题。

如何查看此错误已开启(并在没有解决方案的情况下关闭)https://bugs.php.net/bug.php?id=53831.

但是好消息(不是那么好,因为这个解决方法是从 2012 年开始的):

class DateIntervalFractions extends DateInterval {
    public $milliseconds;
    public function __construct($interval_spec) {
        $this->milliseconds = 0;
        $matches = array();
        preg_match_all("#([0-9]*[.,]?[0-9]*)[S]#",$interval_spec,$matches);
        foreach ($matches[0] as $result)
        {
            $original = $result;
            list($seconds,$milliseconds) = explode(".",substr($result,0,-1));
            $this->milliseconds = $milliseconds / pow(10,strlen($milliseconds) - 3);

            // Replace the milliseconds back to seconds,
            // and let the original constructor do the rest.
            $interval_spec = str_replace($original,$seconds . "S",$interval_spec);
        }
        parent::__construct($interval_spec);
    }
}

这对我来说非常有效!感谢 hotmail dot com 的 jdp2234,您对 php bug track 的评论救了我!

© www.soinside.com 2019 - 2024. All rights reserved.